问题描述:
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 中国