
说得不太明白,向别人问问题应该把问题描述清楚些
是不是实体bean已经添加了一些属性,也在hibernate相关bean的配置文件改好了,不想修改数据库,让程序动态地在数据库添加表的列??
如果是这样的话,你在配置hibernate的配置文件加一下面的属性就可以
<property name="hibernate.hbm2ddl.auto">update</property>
hibernate.hbm2ddl.auto的配置参数,有以下四种:
validate:加载hibernate时,验证创建数据库表结构
create:每次加载hibernate,重新创建数据库表结构,这就是导致数据库表数据丢失的原因。
create-drop:加载hibernate时创建,退出是删除表结构
update:加载hibernate自动更新数据库结构
<bean id="sessionFactory"class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
在applicationContext.xml中加上这个,OK 搞定,hibernate.cfg.xml不用动!
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()
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)