[英]MySQL/Hibernate : Default value for not-null column does not work
org.hibernate.PropertyValueException: not-null property references a
null or transient value
I am using Java,Hibernate and MySQL 5.1.52-log version. 我正在使用Java,Hibernate和MySQL 5.1.52对数版本。
My interpretation of default is if I don't supply value for the column, Hibernate will insert the default value when I try to save this object. 我对默认值的解释是,如果我不为该列提供值,那么当我尝试保存该对象时,Hibernate将插入默认值。
HBM file, HBM文件,
<property name="isActive" type="java.lang.Short">
<column name="IsActive" not-null="true" default="1"/>
</property>
According to the documentation of PropertyValueException, if you set a null value in a property declared not-null="true" and then try to persist/update it, then you will get this exception. 根据PropertyValueException的文档,如果您在声明为not-null =“ true”的属性中设置一个null值,然后尝试对其进行持久化/更新,则将获得此异常。
See http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/PropertyValueException.html 参见http://docs.jboss.org/hibernate/orm/3.5/javadoc/org/hibernate/PropertyValueException.html
You should remove the not-null="true" attribute from the config (because the default value of not-null is false) and then the database should insert the default value that you specified in the configuration for you (in this case '1'). 您应该从配置中删除not-null =“ true”属性(因为not-null的默认值是false),然后数据库应该插入您在配置中为您指定的默认值(在这种情况下为'1 “)。
[UPDATE] [UPDATE]
I would have preferred to put this as a comment in fujy's answer but I am not allowed to comment on other answers yet. 我本来希望将此作为评论在fujy的答案中,但是我还没有评论其他答案。 Does it work as expected if you remove the 'not-null' attribute (As I am showing below)?
如果删除“ not-null”属性,它是否可以按预期工作(如下所示)? I believe that is what is causing the exception that you are getting.
我相信这就是导致您得到异常的原因。
<property name="isActive" type="java.lang.Short">
<meta attribute="default-value">1</meta>
<column name="IsActive" />
</property>
You could simply set it on your model directly 您可以直接在模型上直接进行设置
private Short isActive = 1;
Or you could try this in your hbm
file 或者您可以在
hbm
文件中尝试
<property name="isActive" type="java.lang.Short">
<meta attribute="default-value">1</meta>
<column name="IsActive" not-null="true"/>
</property>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.