The following code is a template for easy Enum mapping.
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;
public class EnumType<E extends Enum<E>> implements UserType {
private static final int[] SQL_TYPES = {Types.VARCHAR};
private Class<E> clazz = null;
protected EnumType(Class<E> clazz) {
this.clazz = clazz;
}
public int[] sqlTypes() {
return SQL_TYPES;
}
public Class<E> returnedClass() {
return clazz;
}
public Object nullSafeGet(ResultSet resultSet, String[] names, Object owner) throws HibernateException, SQLException {
String name = resultSet.getString(names[0]);
E result = null;
if (!resultSet.wasNull()) {
result = Enum.valueOf(clazz, name);
}
return result;
}
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index) throws HibernateException, SQLException {
if (null == value) {
preparedStatement.setNull(index, Types.VARCHAR);
}
else {
preparedStatement.setString(index, ((Enum)value).name());
}
}
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);
}
}
Here is an example Enum:
public ExampleEnum {
ENUM_A,
ENUM_B;
}
Now we just need to create the following custom mapping type:
public class ExampleEnumType extends EnumType<ExampleEnum> {
public ExampleEnumType() {
super(ExampleEnum.class);
}
}
Finally, add it to your mapping file:
<hibernate-mapping> [...] <property name="sample" type="mypackage.MyEnumUserType" not-null="true"/> [...]
Or add it via Annotation:
@Entity
@TypeDef(name = "exampleEnumTypeDef", typeClass = ExampleEnumType.class)
public class Test {
private ExampleEnum exampleEnum;
[...]
@Type(type = "exampleEnumTypeDef")
@Column(name = "example")
public ExampleEnum getExample() {
return exampleEnum;
}
public void setExample(ExampleEnum exampleEnum) {
this.exampleEnum = exampleEnum;
}
}
I helps me very well and I hope you too.
Advertisement