使用自定义用户类型将Hibernate映射字符串值转换为sql枚举

时间:2016-05-06 11:58:05

标签: java hibernate enums

我尝试将字符串值映射到sql enum,但是我收到错误:

Caused by: org.postgresql.util.PSQLException: ERROR: column "state" is of type double_state, and the expression - character varying

我使用以下代码:

.hbm.xml映射条目

<property name="state" type="helper.entity.util.DoubleStateUserType">
    <column name="state" not-null="true"/>
</property>

以下UserType实现nullSafeSet函数:

@Override
    public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index,
                            SessionImplementor session) throws HibernateException, SQLException {
        if (null == value) {
            preparedStatement.setNull(index, Types.VARCHAR);
        } else {
            preparedStatement.setString(index, (String) value);
        }
    }

表中的state列是两个值的枚举。

1 个答案:

答案 0 :(得分:0)

试试这个

<property name="state" column="state" not-null="true">
      <type name="org.hibernate.type.EnumType">
         <param name="enumClass">helper.entity.util.DoubleStateUserType
         <param name="type">12
      </type>
    </property>

默认情况下,当没有指定'type'参数时,Hibernate将枚举值保存为数据库中的整数,我们需要将枚举显示名称存储在数据库中,这样我们就可以将它映射到12,这相当于java.sql.Types .VARCHAR。

相关问题