【发布时间】: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