【问题标题】:Link Enum between PostgresSQL and JavaSpringBoot AP with Hibernate problemPostgresQL 和 Java SpringBoot API 之间的链接枚举与 Hibernate 问题
【发布时间】:2020-04-18 14:33:06
【问题描述】:

我使用的是 Hibernate 5.3.11

我正在尝试在我的 PostgresSQL 数据库和我的代码之间链接一个枚举。

我参考了这些链接来编写我的代码:

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

问题
但我仍然有这个错误:

org.postgresql.util.PSQLException:错误:“天气”列的类型为 weatherenum,但表达式的类型为整数。 提示:您需要重写或转换表达式。

如何解决这个问题?

我的代码

流星实体

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

天气枚举

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

创建枚举的 PgSQL 脚本:

CREATE TYPE WeatherEnum AS ENUM ('sunny','rainy','cloudy','stormy');

【问题讨论】:

  • 请阅读我的代码,我已经阅读了这个主题。我的代码是一样的。
  • 如果我问,那是因为我什么都不懂。因此,如果有知情人士可以帮助我,我将不胜感激......

标签: postgresql hibernate spring-boot enums persistence


【解决方案1】:

看起来您的代码正在运行。我刚刚在本地使用 postgresql12 和 spring-boor 2 进行了测试 这是它在 pgadmin 中的样子

我准备了一个复制器。 https://github.com/ozkanpakdil/spring-examples/tree/master/postgresql-test 一个简单的例子来展示它是如何工作的。你可以从http://localhost:8080/swagger-ui.html 大摇大摆地联系我,我花了一段时间才弄清楚这部分。 swagger 在 SB 2.2 中看起来有问题

这里是示例帖子

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

这就是你得到所有的方法

curl -X GET "http://localhost:8080/api/v1/meteo" -H  "accept: application/json"

【讨论】:

    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多