Hibernate Implementation Mapping Enumeration Type in JSP

  • 2021-12-04 19:24:32
  • OfStack

Hibernate Implementation Mapping Enumeration Type in JSP

Question:

Java BO class Gender is an enumeration type, want to be stored in the database as a string format, how to write hbm. xml?


public enum Gender{  
 UNKNOWN("Unknown"),  
 MALE("Male"),  
 FEMALE("Female"); 
   
 private String key; 
 private Gender(final String key) { 
  this.key = key; 
 } 
 public getGender(String key) { 
  for (Gender gender : Gender.values()) { 
   if (key.euqals(gender.getKey())) 
    return gender;       
  } 
  throw new NoSuchElementException(key); 
 } 
} 

Using UserType:


public class GenderUserType implements UserType {  
 
  private static int[] typeList = { Types.VARCHAR};  
 
 /* 
  * Return the SQL type codes for the columns mapped by this type. 
  * The codes are defined on <tt>java.sql.Types</tt>. */ 
 /** Settings and Gender Class sex Property of the field corresponding to the property SQL Type  */  
 public int[] sqlTypes() { 
   return typeList; 
 } 
 
 /*The class returned by <tt>nullSafeGet()</tt>.*/ 
 /**  Settings GenderUserType Mapped Java Class: Gender Class  */ 
 public Class returnedClass() { 
   return Gender.class;  
 }  
 
 /**  Specify Gender Class is immutable  */  
 public boolean isMutable() { 
   return false; 
 } 
 
 /* 
 * Return a deep copy of the persistent state, stopping at entities and at 
 * collections. It is not necessary to copy immutable objects, or null 
 * values, in which case it is safe to simply return the argument. 
 */ 
 /**  Return Gender Object, due to the Gender Class is immutable,   Therefore, the parameter represented by the Gender Object returns  */  
 public Object deepCopy(Object value) {  
  return (Gender)value;  
 }  
 
 /**  Comparison 1 A Gender Is the object identical to its snapshot  */ 
 public boolean equals(Object x, Object y) { 
  // Because there are only two static constants in memory Gender Example,   
  // So it can be compared directly by memory address   
  return (x == y);  
 }  
 public int hashCode(Object x){  
   return x.hashCode();  
 }  
 
 /* 
 * Retrieve an instance of the mapped class from a JDBC resultset. Implementors 
 * should handle possibility of null values. 
 */ 
 /**  From JDBC ResultSet Read in key And then returns the corresponding Gender Instances  */ 
 public Object nullSafeGet(ResultSet rs, String[] names, Object owner) 
               throws HibernateException, SQLException{  
   // From ResultSet Read in key 
   String sex = (String) Hibernate.STRING.nullSafeGet(rs, names[0]);  
   if (sex == null) { return null; }  
   // Find matching by gender Gender Instances   
   try {  
    return Gender.getGender(sex);  
   }catch (java.util.NoSuchElementException e) {  
    throw new HibernateException("Bad Gender value: " + sex, e);  
   }  
 } 
 
 /* 
 * Write an instance of the mapped class to a prepared statement. Implementors 
 * should handle possibility of null values. 
 * A multi-column type should be written to parameters starting from <tt>index</tt>. 
 */ 
 /**  Put Gender Object's key Attribute to the JDBC PreparedStatement Medium  */ 
 public void nullSafeSet(PreparedStatement st, Object value, int index)  
                throws HibernateException, SQLException{  
  String sex = null;  
  if (value != null)  
    sex = ((Gender)value).getKey();  
  Hibernate.String.nullSafeSet(st, sex, index);  
 }  
 
 /* 
 * Reconstruct an object from the cacheable representation. At the very least this 
 * method should perform a deep copy if the type is mutable. (optional operation) 
 */ 
 public Object assemble(Serializable cached, Object owner){ 
   return cached; 
 }  
  
 /* 
   * Transform the object into its cacheable representation. At the very least this 
   * method should perform a deep copy if the type is mutable. That may not be enough 
   * for some implementations, however; for example, associations must be cached as 
   * identifier values. (optional operation) 
  */ 
  public Serializable disassemble(Object value) { 
     return (Serializable)value;  
  }  
 
 /* 
 * During merge, replace the existing (target) value in the entity we are merging to 
 * with a new (original) value from the detached entity we are merging. For immutable 
 * objects, or null values, it is safe to simply return the first parameter. For 
 * mutable objects, it is safe to return a copy of the first parameter. For objects 
 * with component values, it might make sense to recursively replace component values. 
 */ 
 public Object replace(Object original, Object target, Object owner){ 
    return original;  
 }  
} 

Then define the mapping relationship in hbm. xml:


<hibernate-mapping package="" default-lazy="true" default-cascade="save-update,merge,persist"> 
  <typedef name="Gender" class="com.alpha.hibernate.GenderUserType"> 
    <property name="gender" type="Gender"> 
        <column name="GENDER" not-null="true"> 
        </column> 
    </property> 

Extension:

Defining one UserType for each enumerated type is cumbersome, and one abstract class can be defined.

For example, extend the following example to apply to all enumeration types saved as index


public abstract class OrdinalEnumUserType<E extends Enum<E>> implements UserType {  
 
  protected Class<E> clazz; 
   
  protected OrdinalEnumUserType(Class<E> clazz) { 
    this.clazz = clazz; 
  }  
  
  private static final int[] SQL_TYPES = {Types.NUMERIC};  
  public int[] sqlTypes() {  
    return SQL_TYPES;  
  }  
  
  public Class<?> returnedClass() {  
    return clazz;  
  }  
  
  public E nullSafeGet(ResultSet resultSet, String[] names, Object owner)  
               throws HibernateException, SQLException {     
 
    //Hibernate.STRING.nullSafeGet(rs, names[0]) 
    int index = resultSet.getInt(names[0]); 
    E result = null;  
    if (!resultSet.wasNull()) {  
      result = clazz.getEnumConstants()[index];  
    }  
    return result;  
  }  
  
  public void nullSafeSet(PreparedStatement preparedStatement, 
     Object value,int index) throws HibernateException, SQLException {  
    if (null == value) {  
      preparedStatement.setNull(index, Types.NUMERIC);  
    } else {  
      //Hibernate.String.nullSafeSet(st, sex, index); 
      preparedStatement.setInt(index, ((E)value).ordinal());  
    }  
  }  
  
  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);  
  }  
} 

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: