如何使用创建和更新日期的枚举查找表?

时间:2014-01-23 05:13:38

标签: java spring hibernate enums

我使用Spring + Hibernate来处理数据访问层操作。我想在数据库中使用以下属性创建枚举查找表:

  1. 描述
  2. 创建日期
  3. 更新日期
  4. 我有代码来处理枚举查找表。我不知道如何以其他枚举类可以使用的方式添加创建日期和更新日期。

    有什么建议吗?

1 个答案:

答案 0 :(得分:1)

Enum现在比以往任何时候都更有意义。添加所有数据字段并创建构造函数。 要保存所需的自定义枚举。这里提到了:

public enum Samples implements StringValuedEnum {
SampleA("V", "Sample A"), 
SampleB("M", "Sample B");

private String dbCode;
private String description;

Brand(String dbCode, String description){
    this.setDbCode(dbCode);
    this.setDescription(description);
}


@Override
public String getDbCode() {
    return this.dbCode;
}

public void setDbCode(String dbCode) {
    this.dbCode = dbCode;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}
}

/ ** *用于检查StringValuedEnums的实用程序类。 * /

public class StringValuedEnumReflect {

/**
 * Don't let anyone instantiate this class.
 * 
 * @throws UnsupportedOperationException
 *             Always.
 */
private StringValuedEnumReflect() {
    throw new UnsupportedOperationException(
            "This class must not be instanciated.");
}

/**
 * All Enum constants (instances) declared in the specified class.
 * 
 * @param enumClass
 *            Class to reflect
 * @return Array of all declared EnumConstants (instances).
 */
private static <T extends Enum<T>> T[] getValues(Class<T> enumClass) {
    return enumClass.getEnumConstants();
}

/**
 * All possible string values of the string valued enum.
 * 
 * @param enumClass
 *            Class to reflect.
 * @return Available string values.
 */
public static <T extends Enum<T> & StringValuedEnum> String[] getStringValues(
        Class<T> enumClass) {
    T[] values = getValues(enumClass);
    String[] result = new String[values.length];
    for (int i = 0; i < values.length; i++) {
        result[i] = values[i].getDbCode();
    }
    return result;
}

/**
 * Name of the enum instance which hold the especified string value. If
 * value has duplicate enum instances than returns the first occurency.
 * 
 * @param enumClass
 *            Class to inspect.
 * @param value
 *            String.
 * @return name of the enum instance.
 */
public static <T extends Enum<T> & StringValuedEnum> String getNameFromValue(
        Class<T> enumClass, String value) {
    T[] values = getValues(enumClass);
    for (T v : values) {
        if (v.getDbCode().equals(value)) {
            return v.name();
        }
    }
    return "";
}

}

类扩展EnhancedUserType:

//请注意调用getNameFromValue * ** * ** * ** * ***

 public class StringValuedEnumType<T extends Enum<T> & StringValuedEnum>
    implements EnhancedUserType, ParameterizedType {

/**
 * Enum class for this particular user type.
 */
private Class<T> enumClass;


/** Creates a new instance of ActiveStateEnumType */
public StringValuedEnumType() {
}

@SuppressWarnings("unchecked")
@Override
public void setParameterValues(Properties parameters) {
    String enumClassName = parameters.getProperty("enumClass");
    try {
        enumClass = (Class<T>) Class.forName(enumClassName)
                .asSubclass(Enum.class).asSubclass(StringValuedEnum.class); // Validates
                                                                            // the
                                                                            // class
                                                                            // but
                                                                            // does
                                                                            // not
                                                                            // eliminate
                                                                            // the
                                                                            // cast
    } catch (ClassNotFoundException cnfe) {
        throw new HibernateException("Enum class not found", cnfe);
    }

}

/**
 * The class returned by <tt>nullSafeGet()</tt>.
 * 
 * @return Class
 */
@SuppressWarnings("rawtypes")
public Class returnedClass() {
    return enumClass;
}

public int[] sqlTypes() {
    return new int[] { Types.VARCHAR };
}

public boolean isMutable() {
    return false;
}

/**
 * Retrieve an instance of the mapped class from a JDBC resultset.
 * Implementors should handle possibility of null values.
 * 
 * @param rs
 *            a JDBC result set
 * @param names
 *            the column names
 * @param owner
 *            the containing entity
 * @return Object
 * @throws HibernateException
 * @throws SQLException
 */
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    String value = rs.getString(names[0]);
    if (value == null) { // no default value
        return null;
    }
    String name = getNameFromValue(enumClass, value);
    Object res = rs.wasNull() ? null : Enum.valueOf(enumClass, name);

    return res;
}

/**
 * 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>.
 * 
 * @param st
 *            a JDBC prepared statement
 * @param value
 *            the object to write
 * @param index
 *            statement parameter index
 * @param session
 *            session   
 * @throws HibernateException
 * @throws SQLException
 */
@SuppressWarnings("unchecked")
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
        throws HibernateException, SQLException {
    if (value == null) {
        st.setNull(index, Types.CHAR);
    } else {
        st.setString(index, ((T) value).getDbCode());
    }      
}

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

public Serializable disassemble(Object value) throws HibernateException {
    return (Enum<?>) value;
}

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

public boolean equals(Object x, Object y) throws HibernateException {
    return x == y;
}

public int hashCode(Object x) throws HibernateException {
    return x.hashCode();
}

public Object replace(Object original, Object target, Object owner)
        throws HibernateException {
    return original;
}

@SuppressWarnings("unchecked")
public String objectToSQLString(Object value) {
    return '\'' + ((T) value).getDbCode() + '\'';
}

@SuppressWarnings("unchecked")
public String toXMLString(Object value) {
    return ((T) value).getDbCode();
}

public Object fromXMLString(String xmlValue) {
    String name = getNameFromValue(enumClass, xmlValue);
    return Enum.valueOf(enumClass, name);
}
}

示例实体类

 @Entity

@Table(name =“TCSM_BUS_ENTY”) @DynamicUpdate 公共类SampleClient扩展了java.io.Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "SID")
private Long id;

@Column(name = "SAMPLE_NM")
@Type(type = "com.sample.data.common.StringValuedEnumType", parameters = { @Parameter(name = "enumClass", value = "com.sample.data.model.types.BusinessType") })
private Sample sample;
 }