Hibernate不会保存UserType

时间:2015-01-22 20:01:24

标签: java hibernate logging

我有一个对象(Person),我试图使用Hibernate保存到数据库。 Person有一个Hibernate UserType对象。我无法将Person保存到数据库,我认为问题是UserType。

我已经记录了Sql以查看发生了什么,我注意到记录器已跳过UserType参数。这是因为该值未发送到数据库吗?

insert into person_detail (code, person_type, person_id, name) values (?, ?, ?, ?)

22.01.15 16:16:41 TRACE [main] >>    [org.hibernate.type.descriptor.sql.BasicBinder]  binding parameter [1] as [VARCHAR] - J1
22.01.15 16:16:41 TRACE [main] >>    [org.hibernate.type.descriptor.sql.BasicBinder]  binding parameter [3] as [NUMERIC] - 99
22.01.15 16:16:41 TRACE [main] >>    [org.hibernate.type.descriptor.sql.BasicBinder]  binding parameter [4] as [NUMERIC] - Joe

> <typedef name='PersonType' class='com.TypedefEnumUserTyp'>    <param
> name='enumClassNam'>com.PersonType</param> </typedef>

<subclass name="Person" discriminator-value="PERSON">
    <join table="person_detail">
        <key column="person_id" />
        <property name="person_type" column="person_type" type="PersonType/>
        <property name="code" column="code" />
        <property name="name" column="name" />
    </join>
</subclass> 

public class TypedefEnumUserType extends AbstractToStringUserType implements UserType, Serializable, ParameterizedType {


private Class enumClass;

  public void setParameterValues(Properties params) {

    this.enumClass = classForProp("enumClassName", params);
  }

  public final String toString(Object value) throws HibernateException {
    if (value == null) {
      return null;
    }
    if (value instanceof Enum) {
      final Enum eValue = (Enum) value;
      return eValue.name();
    }
    else {
      final String valueClass = value.getClass().getName();
      throw new IllegalArgumentException("Error trying to convert value to String. Expected instance of Enum, but got " + valueClass);
    }
  }

  @SuppressWarnings("unchecked")
  public final Object fromString(String cached) throws HibernateException {
    if (cached == null) {
      return null;
    }

    try {
      return Enum.valueOf(enumClass, cached);
    }
    catch (IllegalArgumentException iae) {
      throw new SerializationException(enumClass.getName() + " value in database is invalid: " + cached, iae);
    }
  }
}

1 个答案:

答案 0 :(得分:0)

原来我的记录一直在保存。单元测试是在保存后立即删除我的记录所以我认为它没有被保存。我将测试包装在一个事务中,在它运行后回滚。傻我。