我有一个Postgres数据库,我用Hibernate映射,一切正常,直到我需要添加一个新属性。
我添加了一个属性“ROLE”,它必须不为null,默认值为“USER”。
在Postgres我有ROLE VARCHAR(60) NOT NULL DEFAULT 'USER'
我认为是正确的,我也有
@Column(name = "role", length = 60, nullable = false, columnDefinition = "varchar(60) default 'USER'")
public String getRole() {
return this.role;
}
问题是,当我尝试在我的数据库中创建一个新条目时,它失败了 - not-null property references a null or transient value
我已经尝试过一切但没有运气......从我读到的,我所拥有的应该是有效的。 有人可以帮忙吗?
谢谢。
答案 0 :(得分:4)
对于大多数情况,只要将角色设置为默认值即可。
否则它将设置为null
,因为this.role
在保存期间将为null
,因此该值将保持不变。
默认值为字段的初始值:
private String role = "USER";
使用org.hibernate.usertype.UserType
并在保存期间覆盖null
:
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException
{
if (value == null)
st.setString(index, "ROLE");
else
st.setString(index, s);
}
使用@PrePersist
和@PreUpdate
方法并将默认值设置为:
if (this.role == null) { this.role = "USER"; }
如果从外部将对象设置为null,如反序列化的JSON或XML,则可能需要使用@PrePersist
或UserType
,否则只需设置默认值即可。
dynamic-update=true
和dynamic-insert=true
。它为每个插入生成插入语句,该插入语句不会插入空值,因此使用数据库默认值。