简体   繁体   中英

What type to use in Java for column with enum in Postgres?

I am having the following schema in PostgreSQL

student_master(
    enroll_id varchar(6),
    name varchar(25),
    class class_enum
)

Here, class_enum is enum created with

create type class_enum as enum('1','2','3')

Now, I am creating a model class in Java to connect to the database using hibernate. Initially, I declared a "class" column with character data type but I got following exception

org.postgresql.util.PSQLException: ERROR: column "class" is of type class_enum but expression is of type character varying

What type should I use to match this variable in Java class with the PostgreSQL column type?

The best way is to provide enum also on Java side, and let hibernate know how to convert between db value and java.

See The best way to map an Enum Type with JPA and Hibernate

To map this PostgreSQL type we can no longer use the default Hibernate-specific org.hibernate.type.EnumType because PostgreSQL expects an Object type, not a VARCHAR or an INT.

Luckily, we can easily create a custom Type by extending org.hibernate.type.EnumType

public class PostgreSQLEnumType extends org.hibernate.type.EnumType {
 
    public void nullSafeSet(
            PreparedStatement st,
            Object value,
            int index,
            SharedSessionContractImplementor session)
            throws HibernateException, SQLException {
        st.setObject(
            index,
            value != null ?
                ((Enum) value).name() :
                null,
            Types.OTHER
        );
    }
}

In your case, as the values (1, 2, 3) are not valid enum identifiers, you can add a private field in your enum and use that instead of name()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM