英文:
Store Java enums in Postgresql and Hibernate 6 using hbm.xml
问题
我无法弄清楚如何使用Hibernate 6和传统的hbm.xml存储Java Enum,使用Postgresql Enum类型。使用Hibernate 5时,我曾使用hiberate-types
项目并使用以下XML配置:
<property name="type" column="Type" access="field">
<type name="com.vladmihalcea.hibernate.type.basic.PostgreSQLEnumType">
<param name="enumClass">my-java-enum-type</param>
<param name="useNamed">true</param>
</type>
</property>
但是,这在Hibernate 6中不再起作用。包的作者提供了有关如何在注释中使用它的文档,但目前我们无法切换到注释(https://vladmihalcea.com/the-best-way-to-map-an-enum-type-with-jpa-and-hibernate/)。
如果有人能提供一些提示,我将不胜感激。
英文:
I am unable to figure out how to store a Java Enum using a Postgresql Enum Type with Hibernate 6 and the legacy hbm.xml.
With Hibernate 5, I used to use the hiberate-types
project with following XML:
<property name="type" column="Type" access="field">
<type name="com.vladmihalcea.hibernate.type.basic.PostgreSQLEnumType">
<param name="enumClass">"my-java-enum-type"</param>
<param name="useNamed">true</param>
</type>
</property>
But, this is not working with Hibernate 6 anymore. There is a documentation from the package's Author how to use it with annotations, but currently it is not feasible for us to switch to annotations (https://vladmihalcea.com/the-best-way-to-map-an-enum-type-with-jpa-and-hibernate/).
I would be glad if anyone could give a hint.
答案1
得分: 0
我通过编写自己的类型解决了这个问题:
public class PersistentEnum<T extends Enum<T>> extends EnumType<T> {
@Override
public void nullSafeSet(PreparedStatement preparedStatement, T obj, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
if (obj == null) {
preparedStatement.setNull(index, java.sql.Types.OTHER);
} else {
preparedStatement.setObject(index, obj.toString(), java.sql.Types.OTHER);
}
}
}
有了这个,先前发布的 hbm.xml 代码可以正常工作。
英文:
I solved the issue by writing my own type:
public class PersistentEnum<T extends Enum<T>> extends EnumType<T>
{
@Override
public void
nullSafeSet(PreparedStatement preparedStatement, T obj, int index, SharedSessionContractImplementor session) throws HibernateException,
SQLException
{
if(obj == null)
{
preparedStatement.setNull(index, java.sql.Types.OTHER);
}
else
{
preparedStatement.setObject(index, obj.toString(), java.sql.Types.OTHER);
}
}
}
With this, the former posted hbm.xml code is working.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论