我有一个枚举。但每当我发布它时,我的数据都会在数据库中保存为数字 0,1,2。我不知道这是怎么发生的。这就是我将其展示在前面的方式:
import org.hibernate.type.StringType;
import org.hibernate.type.EnumType;
SQLQuery query = getCurrentSession().createSQLQuery(sql.toString());
query.addScalar("id", IntegerType.INSTANCE);
query.addScalar("school",EnumType ); // how to call enumtype here?
我的帖子 Controller :
className.setSchool(SchoolType.FULL); //this is how i'm sending the school value
我的枚举:
public enum SchoolType {
REGULAR("REGULAR"),
FULL("FULL");
private String label;
SchoolType(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public String getName() {
return name();
}
}
在我的实体中这样调用它:
@Column(name="school")
private SchoolType school;
但问题不是作为 reg 或 full ,数据库正在获取 0 或 1 值。如何解决这个问题?我没有获取值,而是获取枚举键作为值。
最佳答案
根据hibernate documentation您应该添加 @Enumerated
注释:
@Enumerated(EnumType.STRING)
@Column(name="school")
private SchoolType school;
如果您想将枚举值存储为枚举值的名称,如 java.lang.Enum#name
默认情况下,hibernate 使用 ORDINAL
枚举映射类型,这就是为什么您的枚举值存储为序数。
关于java - 如何使用 postgresql 在 Spring boot 中的 addScaler() 方法中添加枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61865451/