• 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>
  • 相关阅读:
    装饰器
    函数对象与闭包
    名称空间与作用域
    函数的参数
    函数的基本使用
    ${}与#{}的区别
    thymeleaf之日期格式化
    template might not exist or might not be accessible by any of the configured Template Resolvers
    springboot使用@Scheduled之cron表达式详解
    自定义springboot项目启动图案
  • 原文地址:https://www.cnblogs.com/shamgod/p/5298100.html
Copyright © 2020-2023  润新知