Posts tagged ‘usertype’

package pl.bedkowski.code.userType.EnumSetUserType;

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.EnumSet;
import java.util.List;
import java.util.Set;

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

public class EnumSetUserType<E extends Enum<E>> implements UserType {
	private Class<? extends EnumSet> clazz = null;
	private Class<E> typeClazz = null;
	protected EnumSetUserType(Class<E> c) {
		this.clazz = EnumSet.noneOf(c).getClass();
		typeClazz = c;
	}

	private static final int[] SQL_TYPES = {Types.VARCHAR};
	public int[] sqlTypes() {
		return SQL_TYPES;
	}

	public Class returnedClass() {
		return clazz;
	}

	public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
		String name = resultSet.getString(names[0]);
		EnumSet<E> result = null;
		if (!resultSet.wasNull()) {
			String[] values = name.split(",");
			List<E> enumList = new ArrayList<E>();
			for(String value : values) {
				enumList.add(Enum.valueOf(typeClazz, value));
			}
			result = EnumSet.copyOf(enumList);
		}
		return result;
	}

	public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
		if (null == value) {
			preparedStatement.setNull(index, Types.VARCHAR);
		} else {
			Set<E> values = (Set<E>)value;
			String sqlValue = "";
			if (!values.isEmpty()) {
				StringBuffer buf = new StringBuffer();
				for(E val : values) {
					buf.append(val.name()).append(",");
				}
				sqlValue = buf.substring(0, buf.length() - 1);
			}
			preparedStatement.setString(index, sqlValue);
		}
	}

	public Object deepCopy(Object value) throws HibernateException{
		return value;
	}

	public boolean isMutable() {
		return false;
	}

	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable)value;
	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}
	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}
	public boolean equals(Object x, Object y) throws HibernateException {
		if (x == y)
			return true;
		if (null == x || null == y)
			return false;
		return x.equals(y);
	}
}

Usage

public class User {
    public enum TYPE{admin,guest};
}

///

import pl.bedkowski.code.userType.EnumSetUserType;

public class UserType extends EnumSetUserType<User.TYPE> {
	public UserType() {
		super(User.TYPE.class);
	}
}