HibernateでのUserTypeの使用
1、新しいEmailタイプのフィールド
2、POJO類
3.POJOクラスのマッピング
4、テストの二つの方法
package cn.ehoo.hibernate;
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.apache.commons.lang.StringUtils;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
/**
* @author hy-he
*
*/
public class EMailList implements UserType {
private List emails;
private static final String SPLITTER = ";";
private static final int[] TYPES = new int[] { Types.VARCHAR };
/*
* (non-Javadoc)
*
* @see net.sf.hibernate.UserType#sqlTypes()
*/
public int[] sqlTypes() {
// TODO Auto-generated method stub
return TYPES;
}
/*
* (non-Javadoc)
*
* @see net.sf.hibernate.UserType#returnedClass()
*/
public Class returnedClass() {
// TODO Auto-generated method stub
return List.class;
}
/*
* (non-Javadoc)
*
* @see net.sf.hibernate.UserType#equals(java.lang.Object, java.lang.Object)
*/
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 i = 0; i < xList.size(); i++) {
String str1 = (String) xList.get(i);
String str2 = (String) yList.get(i);
if (!str1.equals(str2))
return false;
}
return true;
}
return false;
}
/**
* email email , list
*/
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
String value = (String) Hibernate.STRING.nullSafeGet(rs, names[0]);
if (value != null) {
return parse(value);
} else {
return null;
}
}
/**
* List email email
*/
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
System.out.println("Set method excecuted");
if (value != null) {
String str = assemble((List) value);
Hibernate.STRING.nullSafeSet(st, str, index);
} else {
Hibernate.STRING.nullSafeSet(st, value, index);
}
}
/*
* (non-Javadoc)
*
* @see net.sf.hibernate.UserType#deepCopy(java.lang.Object)
*/
public Object deepCopy(Object value) throws HibernateException {
List sourcelist = (List) value;
List targetlist = new ArrayList();
targetlist.addAll(sourcelist);
return targetlist;
}
/*
* (non-Javadoc)
*
* @see net.sf.hibernate.UserType#isMutable()
*/
public boolean isMutable() {
// TODO Auto-generated method stub
return false;
}
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();
}
private List parse(String value) {
String[] strs = StringUtils.split(value, 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 {
// TODO Auto-generated method stub
return null;
}
@Override
public Serializable disassemble(Object arg0) throws HibernateException {
// TODO Auto-generated method stub
return null;
}
@Override
public int hashCode(Object arg0) throws HibernateException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Object replace(Object arg0, Object arg1, Object arg2) throws HibernateException {
// TODO Auto-generated method stub
return null;
}
}
2、POJO類
package cn.ehoo.hibernate;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author hy-he
* @hibernate.class table = "USER_TYPE_USER"
*/
public class UserTypeUser implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer age;
private List email = new ArrayList();
/**
* @hibernate.id column = "USER_ID" generator-class = "increment"
* @return
*/
public Long getId() {
return id;
}
/**
* @hibernate.property column = "AGE"
* @return
*/
public Integer getAge() {
return age;
}
/**
* @hibernate.property column = "EMAIL" type =
* "hibernate.usertype.EMailList"
* @return
*/
public List getEmail() {
return email;
}
/**
* @hibernate.property column = "NAME"
* @return
*/
public String getName() {
return name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setEmail(List email) {
this.email = email;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
3.POJOクラスのマッピング
<?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 package="eg">
<class name="cn.ehoo.hibernate.UserTypeUser" table="USER_TYPE_USER" dynamic-update="false" dynamic-insert="false">
<id name="id" column="USER_ID" type="java.lang.Long">
<generator class="increment"></generator>
</id>
<property name="age" type="java.lang.Integer" update="true" insert="true" access="property" column="AGE" />
<property name="email" type="cn.ehoo.hibernate.EMailList" update="true" insert="true" access="property" column="EMAIL" />
<property name="name" type="java.lang.String" update="true" insert="true" access="property" column="NAME" />
<!--
To add non XDoclet property mappings, create a file named
hibernate-properties-UserTypeUser.xml
containing the additional properties and place it in your merge dir.
-->
</class>
</hibernate-mapping>
4、テストの二つの方法
public static void insertUser() throws HibernateException {
UserTypeUser user = new UserTypeUser();
user.setAge(new Integer(23));
user.setName("Test UserType");
user.getEmail().add("[email protected]");
user.getEmail().add("[email protected]");
user.getEmail().add("[email protected]");
user.getEmail().add("[email protected]");
Session session = HibernateUtil.getSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
HibernateUtil.closeSession();
}
public static void display() throws HibernateException {
Session session = HibernateUtil.getSession();
Query query = session.createQuery("from UserTypeUser");
List users = query.list();
HibernateUtil.closeSession();
for (ListIterator iterator = users.listIterator(); iterator.hasNext();) {
UserTypeUser pu = (UserTypeUser) iterator.next();
System.out.println(pu.getName());
List emails = pu.getEmail();
for(int i = 0;i<emails.size();i++){
System.out.println(emails.get(i));
}
}
}