1.

2.

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping > <class name="mypack.Monkey" table="MONKEYS" dynamic-update="true">
<id name="id" type="long" column="ID">
<generator class="increment"/>
</id> <property name="name" column="NAME" /> <property name="homeAddress" type="mypack.AddressUserType" >
<column name="HOME_PROVINCE" />
<column name="HOME_CITY" />
<column name="HOME_STREET"/>
<column name="HOME_ZIPCODE" />
</property> <property name="comAddress" type="mypack.AddressUserType" >
<column name="COM_PROVINCE" />
<column name="COM_CITY" />
<column name="COM_STREET" />
<column name="COM_ZIPCODE" />
</property> <property name="phone" type="mypack.PhoneUserType" column="PHONE" /> </class> </hibernate-mapping>

3.

 package mypack;
import org.hibernate.*;
import org.hibernate.usertype.*;
import java.sql.*;
import java.io.Serializable; public class AddressUserType implements UserType { private static final int[] SQL_TYPES = {Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR}; public int[] sqlTypes() { return SQL_TYPES; } public Class returnedClass() { return Address.class; } public boolean isMutable() { return false; } public Object deepCopy(Object value) {
return value; // Address is immutable
} public boolean equals(Object x, Object y) {
if (x == y) return true;
if (x == null || y == null) return false;
return x.equals(y);
} public int hashCode(Object x){
return x.hashCode();
} public Object nullSafeGet(ResultSet resultSet,String[] names, Object owner)
throws HibernateException, SQLException { String province = resultSet.getString(names[0]);
String city = resultSet.getString(names[1]);
String street = resultSet.getString(names[2]);
String zipcode = resultSet.getString(names[3]); if(province ==null && city==null && street==null && zipcode==null)
return null; return new Address(province,city,street,zipcode);
} public void nullSafeSet(PreparedStatement statement,Object value,int index)
throws HibernateException, SQLException { if (value == null) {
statement.setNull(index, Types.VARCHAR);
statement.setNull(index+1, Types.VARCHAR);
statement.setNull(index+2, Types.VARCHAR);
statement.setNull(index+3, Types.VARCHAR);
} else {
Address address=(Address)value;
statement.setString(index, address.getProvince());
statement.setString(index+1, address.getCity());
statement.setString(index+2, address.getStreet());
statement.setString(index+3, address.getZipcode());
}
} public Object assemble(Serializable cached, Object owner){
return cached;
} public Serializable disassemble(Object value) {
return (Serializable)value;
} public Object replace(Object original,Object target,Object owner){
return original;
}
}

4.

 package mypack;

 import org.hibernate.*;
import org.hibernate.usertype.*;
import java.sql.*;
import java.io.Serializable; public class PhoneUserType implements UserType { private static final int[] SQL_TYPES = {Types.VARCHAR}; public int[] sqlTypes() { return SQL_TYPES; } public Class returnedClass() { return Integer.class; } public boolean isMutable() { return false; } public Object deepCopy(Object value) {
return value; // Integer is immutable
} public boolean equals(Object x, Object y) {
if (x == y) return true;
if (x == null || y == null) return false;
return x.equals(y);
} public int hashCode(Object x){
return x.hashCode();
} public Object nullSafeGet(ResultSet resultSet, String[] names,Object owner)
throws HibernateException, SQLException { String phone = resultSet.getString(names[0]);
//ResultSet的wasNull()方法判断上一次读取的字段(这里为PHONE字段)是否为null
if (resultSet.wasNull()) return null; return new Integer(phone);
} public void nullSafeSet(PreparedStatement statement,Object value,int index)
throws HibernateException, SQLException {
if (value == null) {
statement.setNull(index, Types.VARCHAR);
} else {
String phone=((Integer)value).toString();
statement.setString(index, phone);
}
} public Object assemble(Serializable cached, Object owner){
return cached;
} public Serializable disassemble(Object value) {
return (Serializable)value;
} public Object replace(Object original,Object target,Object owner){
return original;
}
}

5.

 package mypack;

 public class Monkey{
private Long id;
private String name;
private Address homeAddress;
private Address comAddress;
private Integer phone; public Monkey(String name,Address homeAddress, Address comAddress,Integer phone) {
this.name=name;
this.homeAddress = homeAddress;
this.comAddress = comAddress;
this.phone=phone;
} public Monkey() {} public Long getId() {
return this.id;
} private void setId(Long id) {
this.id = id;
} public String getName() {
return this.name;
} public void setName(String name) {
this.name = name;
}
public Address getHomeAddress() {
return this.homeAddress;
} public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
} public Address getComAddress() {
return this.comAddress;
} public void setComAddress(Address comAddress) {
this.comAddress = comAddress;
} public Integer getPhone() {
return this.phone;
} public void setPhone(Integer phone) {
this.phone = phone;
} }

6.

 package mypack;
public class Address{ private final String province;
private final String city;
private final String street;
private final String zipcode; public Address(String province, String city, String street, String zipcode) {
this.street = street;
this.city = city;
this.province = province;
this.zipcode = zipcode; } public String getProvince() {
return this.province;
}
public String getCity() {
return this.city;
} public String getStreet() {
return this.street;
} public String getZipcode() {
return this.zipcode;
} public boolean equals(Object o){
if (this == o) return true;
if (!(o instanceof Address)) return false; final Address address = (Address) o; if(!province.equals(address.province)) return false;
if(!city.equals(address.city)) return false;
if(!street.equals(address.street)) return false;
if(!zipcode.equals(address.zipcode)) return false;
return true;
}
public int hashCode(){
int result;
result= (province==null?0:province.hashCode());
result = 29 * result + (city==null?0:city.hashCode());
result = 29 * result + (street==null?0:street.hashCode());
result = 29 * result + (zipcode==null?0:zipcode.hashCode());
return result;
}
}

7.

 package mypack;

 import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.util.*; public class BusinessService{
public static SessionFactory sessionFactory;
static{
try{
// Create a configuration based on the properties file we've put
Configuration config = new Configuration();
config.configure();
// Get the session factory we can use for persistence
sessionFactory = config.buildSessionFactory();
}catch(RuntimeException e){e.printStackTrace();throw e;}
} public void saveMonkey(){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Monkey monkey=new Monkey();
Address homeAddress=new Address("homeProvince","homeCity","homeStreet","100001");
Address comAddress=new Address("comProvince","comCity","comStreet","200002");
monkey.setName("Tom");
monkey.setHomeAddress(homeAddress);
monkey.setComAddress(comAddress);
monkey.setPhone(new Integer(55556666)); session.save(monkey);
tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
} public void saveAddressSeparately(){
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Address homeAddress=new Address("homeProvince","homeCity","homeStreet","100001");
session.save(homeAddress); tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
// No matter what, close the session
session.close();
}
} public void updateMonkey() {
Session session = sessionFactory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction(); Monkey monkey=(Monkey)session.load(Monkey.class,new Long(1));
Address homeAddress=new Address("homeProvince","homeCity","homeStreet","100001");
Address comAddress=new Address("comProvinceNew","comCityNew","comStreetNew","200002");
monkey.setHomeAddress(homeAddress);
monkey.setComAddress(comAddress); tx.commit(); }catch (RuntimeException e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
// No matter what, close the session
session.close();
}
} public void test(){
saveMonkey();
saveAddressSeparately();
updateMonkey();
} public static void main(String args[]){
new BusinessService().test();
sessionFactory.close();
}
}

8. 

 use sampledb;
drop table if exists MONKEYS;
create table MONKEYS (
ID bigint not null,
NAME varchar(15),
HOME_PROVINCE varchar(15),
HOME_CITY varchar(15),
HOME_STREET varchar(15),
HOME_ZIPCODE varchar(6),
COM_PROVINCE varchar(15),
COM_CITY varchar(15),
COM_STREET varchar(15),
COM_ZIPCODE varchar(6),
PHONE varchar(8), primary key (ID));

9.

 <?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/sampledb
</property>
<property name="connection.username">
root
</property>
<property name="connection.password">
1234
</property> <property name="show_sql">true</property> <mapping resource="mypack/Monkey.hbm.xml" /> </session-factory>
</hibernate-configuration>

Hibernate逍遥游记-第9章 Hibernate的映射类型的更多相关文章

  1. Hibernate逍遥游记-第7章 Hibernate的检索策略和检索方式(<set lazy="false" fetch="join">、left join fetch、FetchMode.JOIN、)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  2. Hibernate逍遥游记-第3章对象-关系映射基础-access="field"、dynamic-insert、dynamic-update、formula、update=false

    1. package mypack; import java.util.*; public class Monkey{ private Long id; private String firstnam ...

  3. Hibernate逍遥游记-第15章处理并发问题-003乐观锁

    1. 2. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; drop table if exists ...

  4. Hibernate逍遥游记-第15章处理并发问题-002悲观锁

    1. 2. hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class=com.mys ...

  5. Hibernate逍遥游记-第13章 映射实体关联关系-006双向多对多(分解为一对多)

    1. 2. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate ...

  6. Hibernate逍遥游记-第13章 映射实体关联关系-005双向多对多(使用组件类集合\<composite-element>\)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  7. Hibernate逍遥游记-第13章 映射实体关联关系-004双向多对多(inverse="true")

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

  8. Hibernate逍遥游记-第13章 映射实体关联关系-003单向多对多

    0. 1. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; create table MONKEYS ...

  9. Hibernate逍遥游记-第13章 映射实体关联关系-002用主键映射一对一(<one-to-one constrained="true">、<generator class="foreign">)

    1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...

随机推荐

  1. openerp 经典收藏 通过view实现字段的只读、隐藏操作(转载)

    通过view实现字段的只读.隐藏操作 原文地址:http://cn.openerp.cn/view_groups/ 在OpenERP V7视图(ir.ui.view)多了一个非常有用的字段(group ...

  2. 图解 CSS: 理解样式表的逻辑(转载)

    原文:http://www.cnblogs.com/del/archive/2009/02/01/1382141.html 样式表可以是外部的.内联的或嵌入的; 链接外部样式文件一般是:<lin ...

  3. PDF打印

    问题: Microsoft Excel 不能访问文件“D:\bwms\源代码\Dcjet.BWMS\Dcjet.Bwms.Web\PrintTmp\Check_bwms.xls”. 可能的原因有以下几 ...

  4. Go学习指南

    学习Golang书籍&资料: 1. The Go Programming Language Specification:  http://golang.org/ref/spec 2. How ...

  5. XCODE快捷键和功能汇总篇(不断更新)

    快捷键 command+b(build) 编译 command+r(run) 运行编译后程序鼠标放在代码元素上,按command然后单击,可以看到元素的属性

  6. iOS 进阶 第十一天(0411)

    0411 UItaBbar的结构 每一个数组都有一个方法,那就是下面这个,如下图所示: 如果想看系统控件是怎么构成的,那么就采用遍历其子控件的方式来做,如上一图中所示 在iOS7及其以后的系统里,控制 ...

  7. iTween基础之Punch(摇晃)

    一.基础介绍:二.基础属性 原文地址 : http://blog.csdn.net/dingkun520wy/article/details/50828042 一.基础介绍 PunchPosition ...

  8. NodeJS从零开始——NPM的使用

    NPM是一个Node包管理和分发工具,已经成为了非官方的发布Node模块(包)的标准.有了NPM,可以很快的找到特定服务要使用的包,进行下载.安装以及管理已经安装的包. NPM常用的命令有: (1)$ ...

  9. VBS基础篇 - 常量

    常量:指的是在程序运行过程中其值保持不变的量,它用来保存固定不变的数值,字符串等常数 . 常量的定义:在vbscript中使用使用 Const 指令可以创建名称具有一定含义的字符串型或数值型常量,并给 ...

  10. HDU 4101 Ali and Baba

    原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=4101 一看之下以为是博弈,后来分析才知道只是搜索题. 首先,我们需要从值为-1的位置由内向外搜索一次, ...