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. 原创的基于HTML/CSS/JavaScript的层级目录树

    之前参加过一些基于HTML/CSS/JavaScript的项目,当在页面中需要生成一颗目录树时,总是首先想着网上有没有现成的生成树的源代码,比如dtree.zthee,或者使用一些javascript ...

  2. yiibooster+bsie

    对于使用yii框架来说,如果使用bootstrap框架的话,现在有一个比较方便的使用途径:yiibooster.官网地址是:http://yii-booster.clevertech.biz/当然,我 ...

  3. EntityFramework常用查询

    Sql语句.存储过程: 1.无参数查询var model = db.Database.SqlQuery<UserInfo>("select* from UserInfoes &q ...

  4. NOIP2015-stone(二分答案)

    这道题在考试时二分答案写炸了,结果得了20分.....同学有用贪心写的(对,贪心!!)都得了30,我感到了深深的恶意.这段时间在忙转语言,现在重新整理一下NOIP的题. 题目来源:vijos 题目如下 ...

  5. 团队项目之Sprint计划会议

    一.我们团队在4月15日进行了冲刺计划会议,会议过程大致如下: 1.总结目前的工作进展,再一次确定所做项目的方向: 2.将之前的调查问卷的结果进行统计,做了需求分析,大致了解了用户的想法: 3.根据初 ...

  6. iOS VideoToolbox硬编H.265(HEVC)H.264(AVC):1 概述

    本文档尝试用Video Toolbox进行H.265(HEVC)硬件编码,视频源为iPhone后置摄像头.去年做完硬解H.264,没做编码,技能上感觉有些缺失.正好刚才发现CMFormatDescri ...

  7. Backbone.Events—纯净MVC框架的双向绑定基石

    Backbone.Events-纯净MVC框架的双向绑定基石 为什么Backbone是纯净MVC? 在这个大前端时代,各路MV*框架如雨后春笋搬涌现出来,在infoQ上有一篇 12种JavaScrip ...

  8. 在ASP.NET MVC应用程序中实现Server.Transfer()类似的功能

    在ASP.NET MVC应用程序中,如果使用Server.Transfer()方法希望将请求转发到其它路径或者Http处理程序进行处理,都会引发“为xxx执行子请求时出错”的HttpException ...

  9. css3选择器笔记

    通用选择器ul~p{}  为ul之后的所有p标签设置属性 (ul和p为同级元素)ul+p{} 仅为ul之后的p标签设置属性 (ul和p为相邻元素)div>p  为div之后的p标签设置属性{ d ...

  10. SQLServer 触发器 同时插入多条记录有关问题

    由于 SQL Server 的触发器, 没有 FOR EACH ROW (ORACL中有)的选项, 有时候不正确的使用 inserted 与deleted 可能会有点麻烦. 下面来一个简单的例子 -- ...