hibernate映射数据库表如何在不插入值的情况下使表中字段默认值生效
問題描述:
?? hibernate技術中對應數(shù)據庫中每一個表,都會有一個映射文件與之對應,此文件描述數(shù)據庫表中每一個字段的類型、長度、是否可空等屬性。在進行表中記錄的插入(更新)操作時,hibernate會根據映射文件中的描述自動生成一個包含所有字段的插入(更新)sql語句,此時如果映射文件中某字段的值為空白(注意:不是null)而其在數(shù)據庫表中定義的默認值不為空白,hibernate會將空白插入到表中,而不會使用此字段的默認值。
比如:在注冊時,設計為有的值(如家庭地址)可填寫或不填寫,因此用到了set***(參數(shù)),此時若傳入的參數(shù)無值(在網頁上未填入家庭地址) ,hibernate會將空白插入到表中,而不會使用此字段的默認值。
解決方法:
?? 在hibernate映射文件對數(shù)據庫表的描述中,在當前字段處加入insert="false"語句,這時hibernate在進行插入操作時,只會為那些有實值的字段賦值,而值為空白的字段就會使用數(shù)據庫表中定義的默認值了。
舉例說明:
表person:
CREATE TABLE?address (
?i_id int(11) NOT NULL auto_increment,
?c_address varchar(100) NOT NULL default '中國',
?PRIMARY KEY? (id)
)
address.hbm.xml:
<hibernate-mapping package="cn.com.lough.model">
?? <class
?????? name="address "
?????? table="address "
?????? 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="C_Address"
?????????? column="c_address "
?????????? type="string"
?????????? not-null="false"
?????????? length="128"
?????? />
</hibernate-mapping>
運行程序
public regAddress(String a){?? //傳入的值a未在網頁文本框里獲得任何值(家庭地址)
Address p = new Address ();
p.setAddress(a);
HiFactory.save(p);
}
此時hibernate生成的sql語句為insert into person(c_address) values('');
數(shù)據庫表結果為
i_id?? c_address
1????? null
修改address.hbm.xml為:
<hibernate-mapping package="cn.com.lough.model">
?? <class
?????? name="Address"
?????? table="address"
?????? 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="C_Address"
?????????? column="c_address"
?????????? type="string"
?????????? not-null="false"
?????????? length="128"
???????????insert="false"
?????? />
</hibernate-mapping>
再次運行程序,此時hibernate生成的sql語句為 insert into address() values();
數(shù)據庫表結果為
i_id?? c_address
1?????
2??????中國
總結
以上是生活随笔為你收集整理的hibernate映射数据库表如何在不插入值的情况下使表中字段默认值生效的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java中类、方法声明为静态的含义
- 下一篇: linux cmake编译源码,linu