使用Hibernate的客户化映射类型

Hibernate提供客户化映射类型接口,使用户能以编程方式创建自定义的映射类型来将持久化类任意类型的属性映射到数据库中。使用客户化映射类型,需要实现org.hibernate.usertype.UserType接口。这是个强大的功能,也是Hibernate的最佳实践之一。我们经常提到ORM中很困难的一点便是O的属性和R的属性不能一一映射,而Hibernate提供的UserType无疑给出了一个很好的解决方案。本文给出使用客户化映射类型的两个例子,算是对Hibernate初学者的抛砖。
    第一个例子是使用UserType映射枚举类型。假设Account表中含有一sex列,类型为tinyint(当前其0代表男,1代表女,将来可能出现2等代表其他性别类型);我们当然可以在对应的Account类中添加int类型的sex属性,但这种数字化无显示意义且类型不安全的枚举不是很好的解决方式,这里就采用了java5的enum来作为Account类的性别属性(如果不熟悉java5的enum,也可采用《effective java》中提到的经典的类型安全的枚举方案)。在Account添加enum Gender:

java 代码
  1. public class Account extends AbstractDomain<Long>{   
  2.        
  3.     public enum Gender{   
  4.         Male("male",0),   
  5.         Female("female",1);   
  6.            
  7.         private String name;   
  8.         private int value;   
  9.            
  10.         public String getName() {   
  11.             return name;   
  12.         }   
  13.         public int getValue() {   
  14.             return value;   
  15.         }   
  16.            
  17.         private Gender(String name,int value){   
  18.             this.name = name;   
  19.             this.value = value;   
  20.         }   
  21.            
  22.         public static Gender getGender(int value){   
  23.             if(0 == value)return Male;   
  24.             else if(1 == value)return Female;   
  25.             else throw new RuntimeException();   
  26.         }   
  27.            
  28.     }   
  29.        
  30.     private Gender gender;   
  31.     public Gender getGender() {   
  32.         return gender;   
  33.     }   
  34.     public void setGender(Gender gender) {   
  35.         this.gender = gender;   
  36.     }   
  37.        //省略其他       
  38. }  
接下来定义实现UserType接口的GenderUserType:
java 代码
  1. public class GenderUserType implements UserType{   
  2.   
  3.     public Object assemble(Serializable arg0, Object arg1) throws HibernateException {   
  4.         return null;   
  5.     }   
  6.   
  7.     /*  
  8.      *  这是用于Hibernate缓存生成的快照,由于Gender是不可变的,直接返回就好了。  
  9.      */  
  10.     public Object deepCopy(Object arg0) throws HibernateException {   
  11.         return arg0;   
  12.     }   
  13.   
  14.     public Serializable disassemble(Object arg0) throws HibernateException {   
  15.         return null;   
  16.     }   
  17.   
  18.     /*  
  19.      * 由于Gender是不可变的,因此直接==了,这个方法将在insert、update时用到。  
  20.      */  
  21.     public boolean equals(Object x, Object y) throws HibernateException {   
  22.         return x == y;   
  23.     }   
  24.   
  25.     public int hashCode(Object o) throws HibernateException {   
  26.         return o.hashCode();   
  27.     }   
  28.   
  29.     /*  
  30.      * 表明Gender是不是可变类(很重要的概念哦),这里的Gender由于是枚举所以是不可变的  
  31.      */  
  32.     public boolean isMutable() {   
  33.         return false;   
  34.     }   
  35.   
  36.     /*  
  37.      *  从ResultSet读取sex并返回Gender实例,这个方法是在从数据库查询数据时用到。  
  38.      */  
  39.     public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {   
  40.         int value = rs.getInt(names[0]);   
  41.         return Account.Gender.getGender(value);   
  42.     }   
  43.   
  44.     /*  
  45.      *  将Gender的value设置到PreparedStatement。  
  46.      */  
  47.     public void nullSafeSet(PreparedStatement ps, Object value, int index) throws HibernateException, SQLException {   
  48.         if(value == null){   
  49.             ps.setInt(index,Account.Gender.Male.getValue());   
  50.         }else{   
  51.             ps.setInt(index,((Account.Gender)value).getValue());   
  52.         }   
  53.     }   
  54.   
  55.     public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {   
  56.         return null;   
  57.     }   
  58.   
  59.     /*  
  60.      * 设置映射的Gender类  
  61.      */  
  62.     public Class returnedClass() {   
  63.         return Account.Gender.class;   
  64.     }   
  65.   
  66.     /*  
  67.      *  设置Gender枚举中的value属性对应的Account表中的sex列的SQL类型  
  68.      */  
  69.     public int[] sqlTypes() {   
  70.         int[] typeList = {Types.TINYINT};   
  71.         return typeList;   
  72.     }   
  73. }  
 最后在Account的配置文件中配置gender属性就好了:
<property name="gender" type="org.prague.domain.util.GenderUserType" column="sex"></property>
    除了可以使用 UserType映射枚举类型,也可以使用Hibernate的PersistentEnum来实现同样的功能,感兴趣的朋友可以参考文章http://www.hibernate.org/203.html。

    
    第二个例子是关于email的。假设Account表中email是一个varchar型的字段,而Account中的Email是如下的类:
java 代码
  1. public class Email {   
  2.     String username;   
  3.   
  4.     String domain;   
  5.   
  6.     public Email() {   
  7.     }   
  8.   
  9.     public Email(String username, String domain) {   
  10.         this.username = username;   
  11.         this.domain = domain;   
  12.     }   
  13.   
  14.     public String getUsername() {   
  15.         return username;   
  16.     }   
  17.   
  18.     public String getDomain() {   
  19.         return domain;   
  20.     }   
  21.   
  22.        
  23.     public void setDomain(String domain) {   
  24.         this.domain = domain;   
  25.     }   
  26.   
  27.     public void setUsername(String username) {   
  28.         this.username = username;   
  29.     }   
  30.   
  31.     public String toString() {   
  32.         return username + '@' + domain;   
  33.     }   
  34.   
  35.     public static Email parse(String email) {   
  36.         Email e = new Email();   
  37.         int at = email.indexOf('@');   
  38.         if (at == -1) {   
  39.             throw new IllegalArgumentException("Invalid email address");   
  40.         }   
  41.   
  42.         e.username = email.substring(0, at);   
  43.         e.domain = email.substring(at + 1);   
  44.   
  45.         return e;   
  46.     }   
  47.   
  48.     @Override  
  49.     public int hashCode() {   
  50.         final int PRIME = 31;   
  51.         int result = 1;   
  52.         result = PRIME * result + ((domain == null) ? 0 : domain.hashCode());   
  53.         result = PRIME * result + ((username == null) ? 0 : username.hashCode());   
  54.         return result;   
  55.     }   
  56.   
  57.     @Override  
  58.     public boolean equals(Object obj) {   
  59.         if (this == obj)    return true;   
  60.       if(null == obj)return false;   
  61.         if (getClass() != obj.getClass())   
  62.             return false;   
  63.         final Email other = (Email) obj;   
  64.         if (domain == null) {   
  65.             if (other.domain != null)   
  66.                 return false;   
  67.         } else if (!domain.equals(other.domain))   
  68.             return false;   
  69.         if (username == null) {   
  70.             if (other.username != null)   
  71.                 return false;   
  72.         } else if (!username.equals(other.username))   
  73.             return false;   
  74.         return true;   
  75.     }   
  76. }   
  77.     email是Account类的一个属性:   
  78. public class Account extends AbstractDomain<Long>{   
  79.        
  80.     private Email email;   
  81.     public Email getEmail() {   
  82.         return email;   
  83.     }   
  84.     public void setEmail(Email email) {   
  85.         this.email = email;   
  86.     }   
  87.   
  88.     //省略其他       
  89. }  
这样的情况下,需要将email的username + '@' + domain映射到Account表的email列,定义一个EmailUserType如下:
java 代码
  1. public class EmailUserType implements UserType{   
  2.   
  3.     public Object assemble(Serializable arg0, Object arg1) throws HibernateException {   
  4.         return null;   
  5.     }   
  6.   
  7.     public Object deepCopy(Object o) throws HibernateException {   
  8.         if(null == o)return null;   
  9.         Email e = (Email)o;   
  10.         return new Email(e.getUsername(),e.getDomain());   
  11.     }   
  12.   
  13.     public Serializable disassemble(Object arg0) throws HibernateException {   
  14.         return null;   
  15.     }   
  16.   
  17.     public boolean equals(Object x, Object y) throws HibernateException {   
  18.         if(x == y)return true;   
  19.         if(x == null || y == null)return false;   
  20.         boolean  f = x.equals(y);   
  21.         return f;   
  22.     }   
  23.   
  24.     public int hashCode(Object o) throws HibernateException {   
  25.         return o.hashCode();   
  26.     }   
  27.   
  28.     public boolean isMutable() {   
  29.         return true;   
  30.     }   
  31.   
  32.     public Object nullSafeGet(ResultSet rs, String[] names, Object o) throws HibernateException, SQLException {   
  33.         String email = rs.getString(names[0]);   
  34.         if(email == null)return null;   
  35.         int index = email.indexOf("@");   
  36.         if(index < 0)throw new RuntimeException();   
  37.         return new Email(email.substring(0,index),email.substring(index+1));   
  38.     }   
  39.   
  40.     public void nullSafeSet(PreparedStatement ps, Object o, int index) throws HibernateException, SQLException {   
  41.         if(o == null )ps.setNull(index, Types.VARCHAR);   
  42.         else{   
  43.             Email e = (Email)o;   
  44.             if(e.getDomain() == null || e.getUsername() == null)ps.setNull(index, Types.VARCHAR);   
  45.             else{   
  46.                 String email = e.getUsername() + "@" + e.getDomain();   
  47.                 ps.setString(index, email);   
  48.             }   
  49.         }   
  50.            
  51.     }   
  52.   
  53.     public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {   
  54.         return null;   
  55.     }   
  56.   
  57.     public Class returnedClass() {   
  58.         return Email.class;   
  59.     }   
  60.   
  61.     public int[] sqlTypes() {   
  62.         int[] typeList = {Types.VARCHAR};   
  63.         return typeList;   
  64.     }   
  65. }  
最后配置下 email 属性:
<property name="email" type="org.prague.domain.util.EmailUserType" column="email"></property>
    相比于Gedner,Email是一个可变类(如果想将其变为不可变类,只需要去掉属性的set方法),因此EmailUserType中的equals要用到Email的equals(hashCode())方法,而deepCopy(Object o) 要做到是深拷贝,否则即便Email属性内容改变,由于Hibernate缓存中的快照指向的对象不变,在update时可能不起作用(在指定了dynamic-update属性的清况下)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值