MySQL / Hibernate:非空列的默认值不起作用 [英] MySQL/Hibernate : Default value for not-null column does not work

查看:361
本文介绍了MySQL / Hibernate:非空列的默认值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  org.hibernate.PropertyValueException:非空属性引用
空值或瞬态值

我使用Java,Hibernate和MySQL 5.1.52-log版本。

我对默认的解释是如果我不' t为列提供值,当我尝试保存这个对象时,Hibernate会插入默认值。

HBM文件,

 < property name =isActivetype =java.lang.Short> 
< column name =IsActivenot-null =truedefault =1/>
< / property>


解决方案

根据PropertyValueException的文档,如果设置在一个声明为not-null =true的属性中使用null值,然后尝试持久化/更新它,然后你会得到这个异常。

参见 http://docs.jboss.org/hibernate/orm/3.5/javadoc/ org / hibernate / PropertyValueException.html



您应该从配置中删除not-null =true属性(因为not-null的默认值是假的),然后数据库应该插入您在配置中为您指定的默认值(在本例中为'1')。

[UPDATE]



我宁愿将此作为对fujy答案的评论,但我不允许对其他答案发表评论。如果删除'not-null'属性(如下所示),它是否按预期工作?

 < property name =isActivetype =java我相信这就是导致异常的原因。 .lang.Short> 
< meta attribute =default-value> 1< / meta>
< column name =IsActive/>
< / property>


org.hibernate.PropertyValueException: not-null property references a 
null or transient value

I am using Java,Hibernate and MySQL 5.1.52-log version.

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.

HBM file,

<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.

See 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').

[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. Does it work as expected if you remove the 'not-null' attribute (As I am showing below)? 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>

这篇关于MySQL / Hibernate:非空列的默认值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆