日期:2014-05-16  浏览次数:20527 次

Hibernate映射自定义数据类型

数据库中存在一个email字段,并允许其中存储多个email地址,各地址之间使用 ; 分割,但是在POJO中,为了便于处理,email定义为一个List对象。
如何将String字段映射为List类型,Hibernate并没有提供原生支持,需要我们实现自己的UserType。
1.数据库定义

DROP   TABLE  t_user;

CREATE   TABLE  t_user (
       id  INT   NOT   NULL  AUTO_INCREMENT
     , name  VARCHAR ( 50 )
     , age  INT
     , email  VARCHAR ( 300 )
     ,  PRIMARY   KEY  (id)
); 

?

2.实现了UserType的自定义数据类型类EmailList

package tuser;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

public class EmailList implements UserType {
	private static final char SPLITTER = ';';
	private static final int[] TYPES = new int[]{Types.VARCHAR};
	
	@Override
	public int[] sqlTypes() {
		return TYPES;
	}

	@Override
	public Class returnedClass() {
		return List.class;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		if(x == y){
			return true;
		}
		
		if(x != null && y != null){
			List xList = (List)x;
			List yList = (List)y;
			
			if(xList.size() != yList.size()){
				return false;
			}
			for(int index = 0; index < xList.size(); index++){
				String str1 = (String) xList.get(index);
				String str2 = (String) yList.get(index);
				if(str1 != str2){
					return false;
				}
			}
			
			return true;
		}
		
		return false;
	}

	@Override
	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {
		String value = Hibernate.STRING.nullSafeGet(rs, names[0]);
		if(value != null){
			return parse(value);
		}else{
			return null;
		}
	}

	@Override
	public void nullSafeSet(PreparedStatement st, Object value, int index)
			throws HibernateException, SQLException {
		System.out.println("Set method executed");
		if(value != null){
			String str = assemble((List)value);
			Hibernate.STRING.nullSafeSet(st, str, index);
		}else{
			Hibernate.STRING.nullSafeSet(st, null, index);
		}
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		List sourceList = (List)value;
		List targetList = new ArrayList();
		targetList.addAll(sourceList);
		
		return targetList;
	}

	@Override
	public boolean isMutable() {
		return false;
	}

	/**
	 * 将String拼装为一个字符串,以“;”分隔
	 * @param emailList
	 * @return
	 */
	private String assemble(List emailList){
		StringBuffer strBuf = new StringBuffer();
		for(int i = 0; i < emailList.size() - 1; i++){
			strBuf.append(emailList.get(i)).append(SPLITTER);
		}
		strBuf.append(emailList.get(emailList.size() - 1));
		
		return strBuf.toString();
	}
	
	/**
	 * 将以“;”分隔的字符串解析为一个字符串数组
	 * @param value
	 * @return
	 */
	private List parse(String value){
		String[] strs = value.split(SPLITTER + "");
		List emailList = new ArrayList();
		for(int i = 0; i < strs.length; i++){
			emailList.add(strs[i]);
		}
		
		return emailList;
	}

	@Override
	public Object assemble(Serializable arg0, Object arg1)
			throws HibernateException {
		return null;
	}

	@Override
	public Serializable disassemble(Object arg0) throws HibernateException {
		return null;
	}

	@Override
	public int hashCode(Object arg0) throws HibernateException {
		return 0;
	}

	@Override
	public Object replace(Object arg0, Object arg1, Object arg2)
			throws HibernateException {
		return null;
	}
}

?

3.配置文件TUser.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="tuser.TUser" table="T_USER">
		<id name="id" type="java.lang.Integer">
			<column name="ID"/>
			&