将Java枚举存储在PostgreSQL和Hibernate 6中,使用hbm.xml文件。

huangapple go评论50阅读模式
英文:

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:

&lt;property name=&quot;type&quot; column=&quot;Type&quot; access=&quot;field&quot;&gt;
		&lt;type name=&quot;com.vladmihalcea.hibernate.type.basic.PostgreSQLEnumType&quot;&gt;
			&lt;param name=&quot;enumClass&quot;&gt;&quot;my-java-enum-type&quot;&lt;/param&gt;
			&lt;param name=&quot;useNamed&quot;&gt;true&lt;/param&gt;
		&lt;/type&gt;
	&lt;/property&gt;

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&lt;T extends Enum&lt;T&gt;&gt; extends EnumType&lt;T&gt;
{
	@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.

huangapple
  • 本文由 发表于 2023年2月7日 01:07:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定