【问题标题】:Hibernate map string value to a sql enum using custom user type使用自定义用户类型将字符串值休眠到 sql 枚举
【发布时间】:2016-05-06 11:58:05
【问题描述】:

我尝试将字符串值映射到 sql 枚举,但出现错误:

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);
        }
    }

表中的状态列是两个值的枚举。

【问题讨论】:

    标签: java hibernate enums


    【解决方案1】:

    试试这个

    <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。

    【讨论】:

    • 我试过这个解决方案,但它只适用于列类型为文本/字符串的情况。如果列类型是 sql 枚举,则不起作用。我在某处读到,sql 枚举是邪恶的,所以现在我将所有枚举重新制作为额外的表。
    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 2017-11-16
    • 1970-01-01
    • 2012-01-16
    • 2012-03-26
    • 2023-03-19
    • 2012-01-25
    • 2018-02-14
    相关资源
    最近更新 更多