package com.shz.usertype;
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;
public class EmailListType implements UserType {
private List emails = null;
private static final char SPLITTER = ';';
private static final int[] TYPES = new int[] { Types.VARCHAR };
@Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return null;
}
public Object deepCopy(Object value) throws HibernateException {
// 创建一个List实例,包含原有List实例的所有元素
List sourceList = (List) value;
List targetList = new ArrayList();
targetList.addAll(sourceList);
return targetList;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
// TODO Auto-generated method stub
return null;
}
public boolean equals(Object x, Object y) throws HibernateException {
// 判断email list是否改变
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 s1 = (String) xList.get(i);
String s2 = (String) yList.get(i);
if (!s1.equals(s2)) {
return false;
}
}
return true;
}
return false;
}
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
public boolean isMutable() {
return false;
}
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
// 从resultSet中取出email字段,并将其解析为List类型返回
String value = (String) Hibernate.STRING.nullSafeGet(rs, names[0]);
if (value != null) {
return parse(value);
} else {
return null;
}
}
private Object 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;
}
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, value.toString(), index);
}
}
private String assemble(List emailList) {
// 将string拼装成一个字符串,以“;”分割
StringBuffer strBuffer = new StringBuffer();
for (int i = 0; i < emailList.size() - 1; i++) {
strBuffer.append(emailList.get(i)).append(SPLITTER);
}
strBuffer.append(emailList.get(emailList.size() - 1));
return strBuffer.toString();
}
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return null;
}
public Class returnedClass() {
return List.class;
}
@Override
public int[] sqlTypes() {
return TYPES;
}
}