Hibernate逍遥游记-第9章 Hibernate的映射类型
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的映射类型的更多相关文章
- Hibernate逍遥游记-第7章 Hibernate的检索策略和检索方式(<set lazy="false" fetch="join">、left join fetch、FetchMode.JOIN、)
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- 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 ...
- Hibernate逍遥游记-第15章处理并发问题-003乐观锁
1. 2. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; drop table if exists ...
- Hibernate逍遥游记-第15章处理并发问题-002悲观锁
1. 2. hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.connection.driver_class=com.mys ...
- Hibernate逍遥游记-第13章 映射实体关联关系-006双向多对多(分解为一对多)
1. 2. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate ...
- Hibernate逍遥游记-第13章 映射实体关联关系-005双向多对多(使用组件类集合\<composite-element>\)
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第13章 映射实体关联关系-004双向多对多(inverse="true")
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
- Hibernate逍遥游记-第13章 映射实体关联关系-003单向多对多
0. 1. drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; create table MONKEYS ...
- Hibernate逍遥游记-第13章 映射实体关联关系-002用主键映射一对一(<one-to-one constrained="true">、<generator class="foreign">)
1. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hi ...
随机推荐
- MySQL excel导入错误 Out of range value adjusted for column
修改my.ini,将 sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"改为 sql ...
- Laravel 5 基础(四)- Blade 简介
在多个页面中我们可能包含相同的内容,像是文件头,链接的css或者js等.我们可以利用布局文件完成这个功能. 让我们新建一个布局文件,例如 views/layout.blade.php <!doc ...
- How to generate number Sequence[AX 2012]
Suppose we want create number sequence for Test field on form in General ledger module Consideratio ...
- [转]WPF 依赖项属性
from:http://blog.csdn.net/datoumimi/article/details/8033682 ps:环境限制,发的东西一长就会被拦截,所以删了一部分 UI软件中经常会用到大量 ...
- Legacy安装win7和Ubuntu14.04双系统
Legacy安装win7和Ubuntu14.04双系统 安装环境 Legacy启动模式(传统引导) 笔记本已安装win7 硬盘启动顺序为: U盘 硬盘 光驱 安装方法 制作U盘启动盘 在Ubuntu官 ...
- FindWindow()&&FindWindowEx
这个函数呢,我一般用来自动刷刷网页啥的比如我最近就在刷52破解的在线时间,好啦怎么用是你自己的事情. FindWindow()主要用来获取目标句柄 或着说窗口的权限 HWND FindWindow( ...
- Cocos2D创建项目
创建项目 配置好开发环境后, 用CMD切换到~\cocos2d\cocos2d-x-2.2.2\tools\project-creator目录上执行以下脚本 python create_project ...
- Eclipse启动的时候窗口一闪就关的解决办法(转)
有时候会碰到如题这种问题,从网上查知解决办法,非常管用 为eclipse.exe创建一个快捷方式,然后快捷方式上右键-属性,在目标栏填入 E:\eclipse\eclipse.exe -vm &quo ...
- C# 越来越复杂了
自从三年前来到现在的公司以后,基本上不怎么使用.NET进行开发了.但最近因为公司有个CRM的项目,所以只有重新检起.NET进行开发. 因为近3年没有搞.NET的开发了,因此也不敢乱整个框架,在看了一周 ...
- 如何使用Xcode6 调试UI,Reveal
实际测试需要使用IOS8并且32-bit的设备:具体打开调试的方法有三种: 1.底部调试菜单中: 2,debug菜单中 3.debug navigator 中