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. RTC搭建android下三层应用程序访问服务器MsSql-客户端

    android下stringgrid已知问题: 通过点击时获取对应行的值有问题,在win下调试正常,在android下出现定位不准 二.客户端开发 1,新建工程 2,添加相关客户端控件TRtcHttp ...

  2. 小课堂Week10 例外处理设计的逆袭Part3

    小课堂Week10 例外处理设计的逆袭Part3 今天是<例外处理设计的逆袭>这本书阅读的第三天,也是最后一天,我们会主要通过实例,对Part2中提出的例外处理等级进行解读. Level1 ...

  3. WPF编译时提示“...不包含适合于入口点的静态‘Main’方法 ...”

    今天看了一下wpf的Application类方面的知识,一个windows应用程序由一个Application类的实例表示,该类跟踪在应用程序中打开的所有窗口,决定何时关闭应用程序(属性 Shutdo ...

  4. JSON对象配合jquery.tmpl.min.js插件,手动攒出一个table

    jquery.tmpl.min.js 首先下载这个插件 1.绑定json那头的键 //TemplateDDMX 这个是这段JS的ID,这个必须写!!!!!! //${}为json的键的值,必须要填写正 ...

  5. Java 线程池框架核心代码分析

    前言 多线程编程中,为每个任务分配一个线程是不现实的,线程创建的开销和资源消耗都是很高的.线程池应运而生,成为我们管理线程的利器.Java 通过Executor接口,提供了一种标准的方法将任务的提交过 ...

  6. 线性判别分析(LDA), 主成分分析(PCA)及其推导【转】

    前言: 如果学习分类算法,最好从线性的入手,线性分类器最简单的就是LDA,它可以看做是简化版的SVM,如果想理解SVM这种分类器,那理解LDA就是很有必要的了. 谈到LDA,就不得不谈谈PCA,PCA ...

  7. MySQL、SqlServer、Oracle三大主流数据库分页查询

    在这里主要讲解一下MySQL.SQLServer2000(及SQLServer2005)和ORCALE三种数据库实现分页查询的方法.可能会有人说这些网上都有,但我的主要目的是把这些知识通过我实际的应用 ...

  8. android 开启或者隐藏软键盘

    一. 隐藏软键盘方法一(注:此方法本人使用时发现isActivie()失效,建议还是用其他方法..): InputMethodManager imm = (InputMethodManager)get ...

  9. 在eclipse里的 flex 没有可视化的编辑

      注:在4.7版本里去掉了可视化编辑器.   转自:http://3470973.blog.51cto.com/3460973/1135328 最近eclipse切换了一个工作空间,创建的flex项 ...

  10. vim插件介绍

    代码补全 http://blog.sina.com.cn/s/blog_a6559d920101acv3.html这个牛逼.************************************** ...