1)在数据库中定义你的属性默认值;
(2)将<class name="User">改为
<class name="User"
dynamic-update="true"
dynamic-insert="true"
>
注释:加上dynamic-insert="true" 即可,说明是动态插入你在数据库中定义好的默认值。dynamic-update="true"相对于更新而言的。
if more lines of text exist in the file, print another page.
namespace designpattern.create.component
{
abstract class component {
protected string name;
public component(string name)
{
this.name = name;
}
hibernate映射数据库表如何使表中字段默认值生效
纯杰宗の0002 | 浏览 2133 次
推荐于2016-02-04 08:55:26最佳答案
解决方法: 在hibernate映射文件对数据库表的描述中,在当前字段处加入insert="false"语句,这时hibernate在进行插入操作时,只会为那些有实值的字段赋值,而值为空白的字段就会使用数据库表中定义的默认值了。
举例说明,表person:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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();
用户登录
还没有账号?立即注册
用户注册
投稿取消
文章分类: |
|
还能输入300字
上传中....