用hibernate时怎么保留默认值

问题描述: 
     hibernate技术中对应数据库中每一个表,都会有一个映射文件与之对应,此文件描述数据库表中每一个字段的类型、长度、是否可空等属性。在进行表中记录的插入(更新)操作时,hibernate会根据映射文件中的描述自动生成一个包含所有字段的插入(更新)sql语句,此时如果映射文件中某字段的值为空(NULL)而其在数据库表中定义的默认值不为空,hibernate会将空值插入到表中,而不会使用此字段的默认值。 

解决方法: 
     在hibernate映射文件对数据库表的描述中,加入dynamic-insert= "true "和   dynamic-update= "true "   语句,这时hibernate在进行插入(更新)操作时,只会为那些值不为空的字段赋值,而值为空的字段就会使用数据库表中定义的默认值了。 


举例说明: 
表person: 
CREATE   TABLE   person   ( 
 i_id   int(11)   NOT   NULL   auto_increment, 
 c_name   varchar(100)   NOT   NULL   default   '张三 ', 
 PRIMARY   KEY     (id) 
)   

person.hbm.xml: 
<hibernate-mapping   package= "cn.com.lough.model "> 
     <class 
             name= "Person " 
             table= "person " 
             lazy= "false " 
     > 
             <meta   attribute= "sync-DAO "> true </meta> 
             <cache   usage= "read-write "/> 
             <id 
                     name= "IId " 
                     type= "integer " 
                     column= "i_id " 
             > 
                     <generator   class= "native "/> 
             </id> 

             <property 
                     name= "CName " 
                     column= "c_name " 
                     type= "string " 
                     not-null= "false " 
                     length= "128 " 
             /> 
</hibernate-mapping> 

运行程序 
Person   p   =   new   Person(); 
HiFactory.save(p); 

此时hibernate生成的sql语句为insert   into   person(c_name)   values(null); 

数据库表结果为 
i_id       c_name 
1             null 

修改person.hbm.xml为: 
<hibernate-mapping   package= "cn.com.lough.model "> 
     <class 
             name= "Person " 
             table= "person " 
             lazy= "false " 
             dynamic-insert= "true " 
     > 
             <meta   attribute= "sync-DAO "> true </meta> 
             <cache   usage= "read-write "/> 
             <id 
                     name= "IId " 
                     type= "integer " 
                     column= "i_id " 
             > 
                     <generator   class= "native "/> 
             </id> 

             <property 
                     name= "CName " 
                     column= "c_name " 
                     type= "string " 
                     not-null= "false " 
                     length= "128 " 
             /> 
</hibernate-mapping> 

再次运行程序,此时hibernate生成的sql语句为   insert   into   person()   values(); 
数据库表结果为 
i_id       c_name 
1             null 
2             张三

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值