postgresql Java 枚举、JPA 和 Postgres 枚举 - 如何让它们协同工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/851758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 23:42:26  来源:igfitidea点击:

Java Enums, JPA and Postgres enums - How do I make them work together?

javapostgresqljpa

提问by Jasper Floor

We have a postgres DB with postgres enums. We are starting to build JPA into our application. We also have Java enums which mirror the postgres enums. Now the big question is how to get JPA to understand Java enums on one side and postgres enums on the other? The Java side should be fairly easy but I'm not sure how to do the postgres side.

我们有一个带有 postgres 枚举的 postgres 数据库。我们开始将 JPA 构建到我们的应用程序中。我们也有反映 postgres 枚举的 Java 枚举。现在最大的问题是如何让 JPA 一方面理解 Java 枚举,另一方面理解 postgres 枚举?Java 方面应该相当简单,但我不确定如何做 postgres 方面。

采纳答案by Arjan Tijms

This involves making multiple mappings.

这涉及进行多个映射。

First, a Postgres enum is returned by the JDBC driver as an instance of type PGObject. The type property of this has the name of your postgres enum, and the value property its value. (The ordinal is not stored however, so technically it's not an enum anymore and possibly completely useless because of this)

首先,JDBC 驱动程序返回 Postgres 枚举作为 PGObject 类型的实例。它的 type 属性具有您的 postgres 枚举的名称,以及 value 属性的值。(然而,序数并未存储,因此从技术上讲,它不再是枚举,因此可能完全没用)

Anyway, if you have a definition like this in Postgres:

无论如何,如果你在 Postgres 中有这样的定义:


CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');

Then the resultset will contain a PGObject with type "mood" and value "happy" for a column having this enum type and a row with the value 'happy'.

然后结果集将包含一个类型为“mood”和值为“happy”的PGObject,用于具有该枚举类型的列和值为“happy”的行。

Next thing to do is writing some interceptor code that sits between the spot where JPA reads from the raw resultset and sets the value on your entity. E.g. suppose you had the following entity in Java:

接下来要做的是编写一些拦截器代码,这些代码位于 JPA 从原始结果集读取并设置实体值的位置之间。例如,假设您在 Java 中有以下实体:


public @Entity class Person {

  public static enum Mood {sad, ok, happy}

  @Id Long ID;
  Mood mood;

}

Unfortunately, JPA does not offer an easy interception point where you can do the conversion from PGObject to the Java enum Mood. Most JPA vendors however have some proprietary support for this. Hibernate for instance has the TypeDef and Type annotations for this (from Hibernate-annotations.jar).

不幸的是,JPA 没有提供一个简单的拦截点,您可以在其中进行从 PGObject 到 Java 枚举 Mood 的转换。然而,大多数 JPA 供应商对此都有一些专有支持。例如,Hibernate 有 TypeDef 和 Type 注释(来自 Hibernate-annotations.jar)。


@TypeDef(name="myEnumConverter", typeClass=MyEnumConverter.class)
public @Entity class Person {

  public static enum Mood {sad, ok, happy}

  @Id Long ID;
  @Type(type="myEnumConverter") Mood mood;

These allow you to supply an instance of UserType (from Hibernate-core.jar) that does the actual conversion:

这些允许您提供执行实际转换的 UserType 实例(来自 Hibernate-core.jar):


public class MyEnumConverter implements UserType {

    private static final int[] SQL_TYPES = new int[]{Types.OTHER};

    public Object nullSafeGet(ResultSet arg0, String[] arg1, Object arg2) throws HibernateException, SQLException {

        Object pgObject = arg0.getObject(X); // X is the column containing the enum

        try {
            Method valueMethod = pgObject.getClass().getMethod("getValue");
            String value = (String)valueMethod.invoke(pgObject);            
            return Mood.valueOf(value);     
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public int[] sqlTypes() {       
        return SQL_TYPES;
    }

    // Rest of methods omitted

}

This is not a complete working solution, but just a quick pointer in hopefully the right direction.

这不是一个完整的工作解决方案,而只是一个指向正确方向的快速指针。

回答by Arthur Nascimento

I've actually been using a simpler way than the one with PGObject and Converters. Since in Postgres enums are converted quite naturally to-from text you just need to let it do what it does best. I'll borrow Arjan's example of moods, if he doesn't mind:

我实际上一直在使用一种比使用 PGObject 和转换器更简单的方法。因为在 Postgres 中枚举是很自然地转换为文本的,所以你只需要让它做它最擅长的事情。如果他不介意的话,我会借用 Arjan 的情绪例子:

The enum type in Postgres:

Postgres 中的枚举类型:

CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');

The class and enum in Java:

Java 中的类和枚举:

public @Entity class Person {

  public static enum Mood {sad, ok, happy};

  @Enumerated(EnumType.STRING)
  Mood mood;

}

}

That @Enumerated tag says that serialization/deserialization of the enum should be done in text. Without it, it uses int, which is more troublesome than anything.

@Enumerated 标记表示枚举的序列化/反序列化应该在文本中完成。没有它就用int,比什么都麻烦。

At this point you have two options. You either:

此时,您有两个选择。你要么:

  1. Add stringtype=unspecifiedto the connection string, as explained in JDBC connection parameters.This lets Postgres guess the right-side type and convert everything adequately, since it receives something like 'enum = unknown', which is an expression it already knows what to do with (feed the ? value to the left-hand type deserialiser). This is the preferred option,as it should work for all simple UDTs such as enums in one go.

    jdbc:postgresql://localhost:5432/dbname?stringtype=unspecified
    
  1. stringtype=unspecified添加到连接字符串,如JDBC 连接参数中所述。这让 Postgres 猜测右侧类型并充分转换所有内容,因为它接收诸如“enum = unknown”之类的东西,这是一个它已经知道要做什么的表达式do with(将 ? 值提供给左侧类型的反序列化器)。这是首选选项,因为它应该一次性适用于所有简单的 UDT,例如枚举。

    jdbc:postgresql://localhost:5432/dbname?stringtype=unspecified
    

Or:

或者:

  1. Create an implicit conversion from varchar to the enum in the database. So in this second case the database receives some assignment or comparison like 'enum = varchar' and it finds a rule in its internal catalog saying that it can pass the right-hand value through the serialization function of varchar followed by the deserialization function of the enum. That's more steps than should be needed; and having too many implicit casts in the catalog can cause arbitrary queries to have ambiguous interpretations, so use it sparingly. The cast creation is:

    CREATE CAST (CHARACTER VARYING as mood) WITH INOUT AS IMPLICIT;

  1. 在数据库中创建从 varchar 到枚举的隐式转换。因此,在第二种情况下,数据库接收一些赋值或比较,如“enum = varchar”,并在其内部目录中找到一条规则,说明它可以通过 varchar 的序列化函数传递右侧值,然后是反序列化函数枚举。这比应该需要的步骤多;并且在目录中有太多的隐式转换会导致任意查询产生歧义的解释,因此请谨慎使用它。演员表创作是:

    CREATE CAST(角色随心情变化)而不是隐式;

Should work with just that.

应该就这样工作。

回答by Stefan L

I filed a bug report with a patch included for Hibernate: HHH-5188

我提交了一个包含 Hibernate 补丁的错误报告:HHH-5188

The patch works for me to read a PostgreSQL enum into a Java enum using JPA.

该补丁适用于我使用 JPA 将 PostgreSQL 枚举读入 Java 枚举。

回答by anton

I found the better solution:

我找到了更好的解决方案:

public class PostgreSQLEnumType extends org.hibernate.type.EnumType {

    public void nullSafeSet(
            PreparedStatement st,
            Object value,
            int index,
            SharedSessionContractImplementor session)
            throws HibernateException, SQLException {
        if(value == null) {
            st.setNull( index, Types.OTHER );
        }
        else {
            st.setObject(
                    index,
                    value.toString(),
                    Types.OTHER
            );
        }
    }
}

Now, we can use the PostgreSQLEnumTypeas follows:

现在,我们可以使用PostgreSQLEnumType如下:

@Entity
@TypeDef(name = "mood", typeClass = PostgreSQLEnumType.class)
public class Person {

    @Enumerated(EnumType.STRING)
    @Type(type = "mood")
    Mood mood;
}