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. Odoo 库存管理-库存移动(Stock Move)新玩法

    库存移动(Stock Move)新玩法 Odoo的库存移动不仅仅是存货在两个“存货地点”之间的移动的基本概念了,他们可以被“串联”在一起,可以用来生成或改变其对应的拣货单 (Picking).链式库存 ...

  2. mysql手工注入

    以下是mynona本人原创的,奉献给大家,不要小看数据库注入 参考: http://www.daydaydata.com/help/sql/advance/limit.html http://www. ...

  3. Python开发【第一篇】Python基础之反射

    反射 反射的作用:反射得作用是提高代码可读行. __import__导入模块和import导入模块的区别: __import__导入模块是通过字符串进行导入. import是常用得导入模块方法. 扩展 ...

  4. 世界级Oracle专家Jonathan Lewis:我很为DBA们的未来担心(图灵访谈)

    部分节选 图灵社区:如果您的子女对计算机科学感兴趣,你会让他们选什么具体的方向呢? JL:我的孩子对计算机科学一点都不感兴趣,甚至对科学都没什么兴趣.他们主修的都是艺术.如果要我给其他的人建议的话,我 ...

  5. Oracle中的if...then...elsif

    if...then...elsif实现多分支判断语句 其语法如下: if <condition_expression1> then plsql_sentence_1; elseif< ...

  6. 在iOS App的图标上显示版本信息

    最近读到一篇文章(http://www.merowing.info/2013/03/overlaying-application-version-on-top-of-your-icon/)介绍了一种非 ...

  7. 执行umount 命令的时候出现 device is busy

    执行umount 命令的时候出现 device is busy ,有人在使用这块磁盘 umount /dev/sde1 umount: /u01/app/oracle: device is busy ...

  8. Zend Studio 12.0.2正式版发布和破解方法,zend studio 12.0.1汉化,相式设置为Dreamweaver,空格缩进为4个, 代码默认不折叠的设置,Outline中使用的图形标志,代码颜色之eot设置。

    背景:zend studio 12.0.2 修复了一个12.0.1的:  Fixed problem with referenced variables marked as undefined,我都说 ...

  9. Hadoop启动异常情况解决方案

    1. 启动时报WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using b ...

  10. 瞧一瞧,看一看呐,用MVC+EF快速弄出一个CRUD,一行代码都不用写,真的一行代码都不用写!!!!

    瞧一瞧,看一看呐用MVC+EF快速弄出一个CRUD,一行代码都不用写,真的一行代码都不用写!!!! 现在要写的呢就是,用MVC和EF弄出一个CRUD四个页面和一个列表页面的一个快速DEMO,当然是在不 ...