hibernate映射數據庫表如何在不插入值的情況下使表中字段默認值生效

問題描述:
   hibernate技術中對應數據庫中每一個表,都會有一個映射文件與之對應,此文件描述數據庫表中每一個字段的類型、長度、是否可空等屬性。在進行表中記錄的插入(更新)操作時,hibernate會根據映射文件中的描述自動生成一個包含所有字段的插入(更新)sql語句,此時如果映射文件中某字段的值爲空白(注意:不是null)而其在數據庫表中定義的默認值不爲空白,hibernate會將空白插入到表中,而不會使用此字段的默認值。

比如:在註冊時,設計爲有的值(如家庭地址)可填寫或不填寫,因此用到了set***(參數),此時若傳入的參數無值(在網頁上未填入家庭地址) ,hibernate會將空白插入到表中,而不會使用此字段的默認值。

解決方法:
   在hibernate映射文件對數據庫表的描述中,在當前字段處加入insert="false"語句,這時hibernate在進行插入操作時,只會爲那些有實值的字段賦值,而值爲空白的字段就會使用數據庫表中定義的默認值了。


舉例說明:
表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('');

數據庫表結果爲
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();
數據庫表結果爲
i_id   c_address
1     
2      中國
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章