0

I am using Hibernate 5.3.11

I'm trying to link an Enum between my PostgresSQL database and my code.

I referred to these links to make my code :

Hibernate mapping between PostgreSQL enum and Java enum
Java Enums, JPA and Postgres enums - How do I make them work together?

Problem
But I still have that error :

org.postgresql.util.PSQLException: ERROR: the column "weather" is of type weatherenum but the expression is of type integer. Hint: You will need to rewrite or cast the expression.

How solve this problem ?

My code

Meteo entity

//package and imports

@Entity
@TypeDef(
        name = "pgsql_enum",
        typeClass = PostgreSQLEnumType.class
)
public class Meteo {
    private Integer id;

    @Enumerated(EnumType.STRING)
    @Column(columnDefinition = "weatherenum")
    @Type( type = "pgsql_enum" )
    private WeatherEnum weather;
    ...

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() { return id; }

    public void setId(Integer id) { this.id = id; }

    @Basic
    @Column(name = "weather")
    public WeatherEnum getWeather() { return weather; }

    public void setWeather(WeatherEnum weather) {
        this.weather = weather;
    }

   .
   .
   .

}

PostgreSQLEnumType

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

WeatherEnum

public enum WeatherEnum {
    sunny, cloudy, stormy, rainy;
}

PgSQL Script to create enum:

CREATE TYPE WeatherEnum AS ENUM ('sunny','rainy','cloudy','stormy');
Ugo Evola
  • 546
  • 3
  • 8
  • 19

1 Answers1

0

Looks like your code is working. I just tested in my local with postgresql12 and spring-boor 2 here is how it looks in pgadmin enter image description here

I prepared a reproducer. https://github.com/ozkanpakdil/spring-examples/tree/master/postgresql-test simple example to show how it works. you can reach to swagger from http://localhost:8080/swagger-ui.html took me a while to figure out this part. swagger looks like having problem in SB 2.2

here is example post

curl -X POST "http://localhost:8080/api/v1/meteo" -H  "accept: */*" -H  "Content-Type: application/json" -d "{  \"weather\": \"rainy\"}"

and here is how you get all

curl -X GET "http://localhost:8080/api/v1/meteo" -H  "accept: application/json"
ozkanpakdil
  • 3,199
  • 31
  • 48