我正在使用Hibernate 5.3.11
我正在尝试在我的PostgresSQL数据库和我的代码之间链接一个枚举。
我引用这些链接来编写代码:
Hibernate mapping between PostgreSQL enum and Java enumJava 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
);
}
}
}
WeatherEnum
public enum WeatherEnum {
sunny, cloudy, stormy, rainy;
}
用于创建枚举的PgSQL脚本:
CREATE TYPE WeatherEnum AS ENUM ('sunny','rainy','cloudy','stormy');
看起来您的代码正在运行。我刚刚在本地使用postgresql12和spring-boor 2进行了测试这是在pgadmin中的样子
我准备了一个复制器。 https://github.com/ozkanpakdil/spring-examples/tree/master/postgresql-test简单示例演示其工作原理。您可以从http://localhost:8080/swagger-ui.html花费我一些时间来弄清楚这部分。大摇大摆似乎在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"