无法在Hibernate中设置属性的默认值 [英] Doesn't work setting default value of property in Hibernate
问题描述
我在我的实体中有一个布尔属性。这是我的注释:
@Column(name =IS_ACTIVE,nullable = false,columnDefinition =BIT DEFAULT 1 ,length = 1)
public Boolean getActive(){
return isActive;
但是 columnDefinition =BIT DEFAULT 1 code>并不完美。这里是我得到的生成表的SQL代码:
IS_ACTIVE BIT(1)NOT NULL,
我做错了什么?
所以当我试图保存
`com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:这个类的一个实例到数据库我得到这个异常:列'IS_ACTIVE'不能为空'
如果我删除 nullable = false
property:
@Column(name =IS_ACTIVE,columnDefinition =BIT DEFAULT 1,length = 1)
public Boolean getActive(){
return isActive;
}
所以我可以在这种情况下保存创建的对象。但它仍然是默认值未设置,并且我在数据库的该字段的值中获得NULL。
有什么想法吗?如果它很重要,我使用MySQL Server 5.1。我会非常感谢任何帮助。提前感谢!
BOOLEAN
数据类型,定义您的 @Column
这样的注解: @Column(name =IS_ACTIVE ,columnDefinition =boolean default true,nullable = false)
private布尔值active = true;
I have a boolean property in my entity. Here's my annotations for it:
@Column(name = "IS_ACTIVE", nullable = false, columnDefinition="BIT DEFAULT 1", length = 1)
public Boolean getActive() {
return isActive;
}
But columnDefinition="BIT DEFAULT 1"
doen't work perfectly. Here's SQL code I get as result for generated table:
IS_ACTIVE BIT(1) NOT NULL,
What am I doing wrong?
And so when I try to save an instance of this class to the database I get the exception:
`com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'IS_ACTIVE' cannot be null`
If I remove nullable = false
property:
@Column(name = "IS_ACTIVE", columnDefinition="BIT DEFAULT 1", length = 1)
public Boolean getActive() {
return isActive;
}
so I can save a created object in this case. But it's still the default value is not set and I get NULL in the value of this field in database.
Any ideas please? I use MySQL Server 5.1 if it's important. I would be very grateful for any help. Thanks in advance!
Try using BOOLEAN
data type, define your @Column
annotation like that:
@Column(name = "IS_ACTIVE", columnDefinition = "boolean default true", nullable = false)
private Boolean active = true;
这篇关于无法在Hibernate中设置属性的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!