Hibernate逍遥游记-第9章 Hibernate的映射类型

2023-11-01 05:30

本文主要是介绍Hibernate逍遥游记-第9章 Hibernate的映射类型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.

2.

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping
 3 PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 4 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 5 <hibernate-mapping >
 6 
 7   <class name="mypack.Monkey" table="MONKEYS" dynamic-update="true">
 8     <id name="id" type="long" column="ID">
 9       <generator class="increment"/>
10     </id>
11 
12     <property name="name" column="NAME" />
13     
14     <property name="homeAddress" type="mypack.AddressUserType" >
15         <column name="HOME_PROVINCE" />
16         <column name="HOME_CITY" />
17         <column name="HOME_STREET"/>
18         <column name="HOME_ZIPCODE" />
19     </property>
20 
21     <property name="comAddress" type="mypack.AddressUserType" >
22         <column name="COM_PROVINCE" />
23         <column name="COM_CITY" />
24         <column name="COM_STREET" />
25         <column name="COM_ZIPCODE" />
26     </property>
27 
28 
29     <property name="phone" type="mypack.PhoneUserType" column="PHONE" />
30     
31   </class>
32 
33 </hibernate-mapping>

 

3.

 1 package mypack;
 2 import org.hibernate.*;
 3 import org.hibernate.usertype.*;
 4 import java.sql.*;
 5 import java.io.Serializable;
 6 
 7 public class AddressUserType implements UserType {
 8 
 9   private static final int[] SQL_TYPES = {Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR};
10 
11   public int[] sqlTypes() { return SQL_TYPES; }
12 
13   public Class returnedClass() { return Address.class; }
14 
15   public boolean isMutable() { return false; }
16 
17   public Object deepCopy(Object value) {
18     return value; // Address is immutable
19   }
20 
21   public boolean equals(Object x, Object y) {
22     if (x == y) return true;
23     if (x == null || y == null) return false;
24     return x.equals(y);
25   }
26 
27   public int hashCode(Object x){
28     return x.hashCode();
29   }
30   
31   public Object nullSafeGet(ResultSet resultSet,String[] names, Object owner)
32   throws HibernateException, SQLException {
33 
34     String province = resultSet.getString(names[0]);
35     String city = resultSet.getString(names[1]);
36     String street = resultSet.getString(names[2]);
37     String zipcode = resultSet.getString(names[3]);
38 
39     if(province ==null  && city==null  && street==null  && zipcode==null)
40       return null;
41 
42     return new Address(province,city,street,zipcode);
43   }
44 
45   public void nullSafeSet(PreparedStatement statement,Object value,int index)
46   throws HibernateException, SQLException {
47 
48     if (value == null) {
49       statement.setNull(index, Types.VARCHAR);
50       statement.setNull(index+1, Types.VARCHAR);
51       statement.setNull(index+2, Types.VARCHAR);
52       statement.setNull(index+3, Types.VARCHAR);
53     } else {
54       Address address=(Address)value;
55       statement.setString(index, address.getProvince());
56       statement.setString(index+1, address.getCity());
57       statement.setString(index+2, address.getStreet());
58       statement.setString(index+3, address.getZipcode());
59     }
60   }
61 
62   public Object assemble(Serializable cached, Object owner){
63     return cached;
64   }
65 
66   public Serializable disassemble(Object value) {
67     return (Serializable)value;
68   }
69   
70   public Object replace(Object original,Object target,Object owner){
71     return original;
72   }
73 }

 

4.

 1 package mypack;
 2 
 3 import org.hibernate.*;
 4 import org.hibernate.usertype.*;
 5 import java.sql.*;
 6 import java.io.Serializable;
 7 
 8 public class PhoneUserType implements UserType {
 9 
10   private static final int[] SQL_TYPES = {Types.VARCHAR};
11 
12   public int[] sqlTypes() { return SQL_TYPES; }
13 
14   public Class returnedClass() { return Integer.class; }
15 
16   public boolean isMutable() { return false; }
17 
18   public Object deepCopy(Object value) {
19     return value; // Integer is immutable
20   }
21 
22   public boolean equals(Object x, Object y) {
23     if (x == y) return true;
24     if (x == null || y == null) return false;
25     return x.equals(y);
26   }
27 
28   public int hashCode(Object x){
29     return x.hashCode();
30   }
31 
32   public Object nullSafeGet(ResultSet resultSet, String[] names,Object owner)
33     throws HibernateException, SQLException {
34 
35     String phone = resultSet.getString(names[0]);
36     //ResultSet的wasNull()方法判断上一次读取的字段(这里为PHONE字段)是否为null
37     if (resultSet.wasNull()) return null;
38 
39     return new Integer(phone);
40   }
41 
42   public void nullSafeSet(PreparedStatement statement,Object value,int index)
43   throws HibernateException, SQLException {
44     if (value == null) {
45       statement.setNull(index, Types.VARCHAR);
46     } else {
47       String phone=((Integer)value).toString();
48       statement.setString(index, phone);
49     }
50   }
51 
52   public Object assemble(Serializable cached, Object owner){
53     return cached;
54   }
55 
56   public Serializable disassemble(Object value) {
57     return (Serializable)value;
58   }
59   
60   public Object replace(Object original,Object target,Object owner){
61     return original;
62   }
63 }

 

5.

 1 package mypack;
 2 
 3 public class Monkey{
 4     private Long id;
 5     private String name;
 6     private Address homeAddress;
 7     private Address comAddress;
 8     private Integer phone;
 9 
10     public Monkey(String name,Address homeAddress, Address comAddress,Integer phone) {
11         this.name=name;
12         this.homeAddress = homeAddress;
13         this.comAddress = comAddress;
14         this.phone=phone;
15     }
16 
17 
18     public Monkey() {}
19 
20     public Long getId() {
21         return this.id;
22     }
23 
24     private void setId(Long id) {
25         this.id = id;
26     }
27 
28     public String getName() {
29         return this.name;
30     }
31 
32     public void setName(String name) {
33         this.name = name;
34     }
35     public Address getHomeAddress() {
36         return this.homeAddress;
37     }
38 
39     public void setHomeAddress(Address homeAddress) {
40         this.homeAddress = homeAddress;
41     }
42 
43     public Address getComAddress() {
44         return this.comAddress;
45     }
46 
47     public void setComAddress(Address comAddress) {
48         this.comAddress = comAddress;
49     }
50 
51     public Integer getPhone() {
52         return this.phone;
53     }
54 
55     public void setPhone(Integer phone) {
56         this.phone = phone;
57     }
58 
59 }

 

6.

 1 package mypack;
 2 public class Address{
 3 
 4     private final String province;
 5     private final String city;
 6     private final String street;
 7     private final String zipcode;
 8 
 9     public Address(String province, String city, String street, String zipcode) {
10         this.street = street;
11         this.city = city;
12         this.province = province;
13         this.zipcode = zipcode;
14 
15     }
16 
17     public String getProvince() {
18         return this.province;
19     }
20     public String getCity() {
21         return this.city;
22     }
23 
24     public String getStreet() {
25         return this.street;
26     }
27 
28     public String getZipcode() {
29         return this.zipcode;
30     }
31 
32 
33     public boolean equals(Object o){
34         if (this == o) return true;
35         if (!(o instanceof Address)) return false;
36 
37      final Address address = (Address) o;
38 
39      if(!province.equals(address.province)) return false;
40      if(!city.equals(address.city)) return false;
41      if(!street.equals(address.street)) return false;
42      if(!zipcode.equals(address.zipcode)) return false;
43      return true;
44     }
45     public int hashCode(){
46         int result;
47     result= (province==null?0:province.hashCode());
48     result = 29 * result + (city==null?0:city.hashCode());
49         result = 29 * result + (street==null?0:street.hashCode());
50         result = 29 * result + (zipcode==null?0:zipcode.hashCode());
51     return result;
52     }
53 }

 

7.

  1 package mypack;
  2 
  3 import org.hibernate.*;
  4 import org.hibernate.cfg.Configuration;
  5 import java.util.*;
  6 
  7 public class BusinessService{
  8   public static SessionFactory sessionFactory;
  9   static{
 10      try{
 11       // Create a configuration based on the properties file we've put
 12        Configuration config = new Configuration();
 13        config.configure();
 14       // Get the session factory we can use for persistence
 15       sessionFactory = config.buildSessionFactory();
 16     }catch(RuntimeException e){e.printStackTrace();throw e;}
 17   }
 18 
 19 
 20   public void saveMonkey(){
 21     Session session = sessionFactory.openSession();
 22     Transaction tx = null;
 23     try {
 24       tx = session.beginTransaction();
 25 
 26       Monkey monkey=new Monkey();
 27       Address homeAddress=new Address("homeProvince","homeCity","homeStreet","100001");
 28       Address comAddress=new Address("comProvince","comCity","comStreet","200002");
 29       monkey.setName("Tom");
 30       monkey.setHomeAddress(homeAddress);
 31       monkey.setComAddress(comAddress);
 32       monkey.setPhone(new Integer(55556666));
 33        
 34       session.save(monkey);
 35       tx.commit();
 36 
 37     }catch (RuntimeException e) {
 38       if (tx != null) {
 39         tx.rollback();
 40       }
 41       throw e;
 42     } finally {
 43       // No matter what, close the session
 44       session.close();
 45     }
 46   }
 47 
 48 
 49   public void saveAddressSeparately(){
 50     Session session = sessionFactory.openSession();
 51     Transaction tx = null;
 52     try {
 53       tx = session.beginTransaction();
 54 
 55       Address homeAddress=new Address("homeProvince","homeCity","homeStreet","100001");
 56       session.save(homeAddress);
 57 
 58       tx.commit();
 59 
 60     }catch (RuntimeException e) {
 61       if (tx != null) {
 62         tx.rollback();
 63       }
 64       e.printStackTrace();
 65     } finally {
 66       // No matter what, close the session
 67       session.close();
 68     }
 69   }
 70 
 71   public void updateMonkey() {
 72     Session session = sessionFactory.openSession();
 73     Transaction tx = null;
 74     try {
 75       tx = session.beginTransaction();
 76 
 77       Monkey monkey=(Monkey)session.load(Monkey.class,new Long(1));
 78       Address homeAddress=new Address("homeProvince","homeCity","homeStreet","100001");
 79       Address comAddress=new Address("comProvinceNew","comCityNew","comStreetNew","200002");
 80       monkey.setHomeAddress(homeAddress);
 81       monkey.setComAddress(comAddress);
 82 
 83       tx.commit();
 84 
 85     }catch (RuntimeException e) {
 86       if (tx != null) {
 87         tx.rollback();
 88       }
 89       throw e;
 90     } finally {
 91       // No matter what, close the session
 92       session.close();
 93     }
 94   }
 95 
 96   public void test(){
 97       saveMonkey();
 98       saveAddressSeparately();
 99       updateMonkey();
100   }
101 
102   public static void main(String args[]){
103     new BusinessService().test();
104     sessionFactory.close();
105   }
106 }

 

8. 

 1 use sampledb;
 2 drop table if exists MONKEYS;
 3 create table MONKEYS (
 4 ID bigint not null, 
 5 NAME varchar(15), 
 6 HOME_PROVINCE varchar(15), 
 7 HOME_CITY varchar(15), 
 8 HOME_STREET varchar(15), 
 9 HOME_ZIPCODE varchar(6),
10 COM_PROVINCE varchar(15), 
11 COM_CITY varchar(15), 
12 COM_STREET varchar(15), 
13 COM_ZIPCODE varchar(6), 
14 PHONE varchar(8), primary key (ID));

 

9.

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <!DOCTYPE hibernate-configuration
 3  PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
 4  "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 
 6 <hibernate-configuration>
 7     <session-factory>
 8         <property name="dialect">
 9             org.hibernate.dialect.MySQLDialect
10         </property>
11         <property name="connection.driver_class">
12             com.mysql.jdbc.Driver
13         </property>
14         <property name="connection.url">
15             jdbc:mysql://localhost:3306/sampledb
16         </property>
17         <property name="connection.username">
18             root
19         </property>
20         <property name="connection.password">
21             1234
22         </property>
23 
24         <property name="show_sql">true</property>
25 
26         <mapping resource="mypack/Monkey.hbm.xml" />
27 
28     </session-factory>
29 </hibernate-configuration>

 

转载于:https://www.cnblogs.com/shamgod/p/5298100.html

这篇关于Hibernate逍遥游记-第9章 Hibernate的映射类型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/320807

相关文章

Rust中的BoxT之堆上的数据与递归类型详解

《Rust中的BoxT之堆上的数据与递归类型详解》本文介绍了Rust中的BoxT类型,包括其在堆与栈之间的内存分配,性能优势,以及如何利用BoxT来实现递归类型和处理大小未知类型,通过BoxT,Rus... 目录1. Box<T> 的基础知识1.1 堆与栈的分工1.2 性能优势2.1 递归类型的问题2.2

Python如何计算两个不同类型列表的相似度

《Python如何计算两个不同类型列表的相似度》在编程中,经常需要比较两个列表的相似度,尤其是当这两个列表包含不同类型的元素时,下面小编就来讲讲如何使用Python计算两个不同类型列表的相似度吧... 目录摘要引言数字类型相似度欧几里得距离曼哈顿距离字符串类型相似度Levenshtein距离Jaccard相

Go语言中三种容器类型的数据结构详解

《Go语言中三种容器类型的数据结构详解》在Go语言中,有三种主要的容器类型用于存储和操作集合数据:本文主要介绍三者的使用与区别,感兴趣的小伙伴可以跟随小编一起学习一下... 目录基本概念1. 数组(Array)2. 切片(Slice)3. 映射(Map)对比总结注意事项基本概念在 Go 语言中,有三种主要

Java中基于注解的代码生成工具MapStruct映射使用详解

《Java中基于注解的代码生成工具MapStruct映射使用详解》MapStruct作为一个基于注解的代码生成工具,为我们提供了一种更加优雅、高效的解决方案,本文主要为大家介绍了它的具体使用,感兴趣... 目录介绍优缺点优点缺点核心注解及详细使用语法说明@Mapper@Mapping@Mappings@Co

Redis的Zset类型及相关命令详细讲解

《Redis的Zset类型及相关命令详细讲解》:本文主要介绍Redis的Zset类型及相关命令的相关资料,有序集合Zset是一种Redis数据结构,它类似于集合Set,但每个元素都有一个关联的分数... 目录Zset简介ZADDZCARDZCOUNTZRANGEZREVRANGEZRANGEBYSCOREZ

在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码

《在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码》在MyBatis的XML映射文件中,trim元素用于动态添加SQL语句的一部分,处理前缀、后缀及多余的逗号或连接符,示... 在MyBATis的XML映射文件中,<trim>元素用于动态地添加SQL语句的一部分,例如SET或W

IDEA如何将String类型转json格式

《IDEA如何将String类型转json格式》在Java中,字符串字面量中的转义字符会被自动转换,但通过网络获取的字符串可能不会自动转换,为了解决IDEA无法识别JSON字符串的问题,可以在本地对字... 目录问题描述问题原因解决方案总结问题描述最近做项目需要使用Ai生成json,可生成String类型

Mysql 中的多表连接和连接类型详解

《Mysql中的多表连接和连接类型详解》这篇文章详细介绍了MySQL中的多表连接及其各种类型,包括内连接、左连接、右连接、全外连接、自连接和交叉连接,通过这些连接方式,可以将分散在不同表中的相关数据... 目录什么是多表连接?1. 内连接(INNER JOIN)2. 左连接(LEFT JOIN 或 LEFT

Redis的Hash类型及相关命令小结

《Redis的Hash类型及相关命令小结》edisHash是一种数据结构,用于存储字段和值的映射关系,本文就来介绍一下Redis的Hash类型及相关命令小结,具有一定的参考价值,感兴趣的可以了解一下... 目录HSETHGETHEXISTSHDELHKEYSHVALSHGETALLHMGETHLENHSET

Python中异常类型ValueError使用方法与场景

《Python中异常类型ValueError使用方法与场景》:本文主要介绍Python中的ValueError异常类型,它在处理不合适的值时抛出,并提供如何有效使用ValueError的建议,文中... 目录前言什么是 ValueError?什么时候会用到 ValueError?场景 1: 转换数据类型场景