关于Spring整合Hibernate中自动建表

本文介绍了如何使用Hibernate在启动时自动创建或更新数据库表结构。包括了直接使用Hibernate及Spring MVC整合Hibernate的方法,并展示了JPA环境下persistence.xml的配置细节。
1、在单独的使用Hibernate时,在Hibernate映射文件(*.hbm.xml)中配置好各个类的关系,然后再Hibernate配置文件(hibernate.cfg.xml)中添加属性可以自动在数据库中创建表结构(注:只能创建表,而非创建库)。

主要代码如下:

<!--自动在数据库中建立表 -->
<property name="hbm2ddl.auto">create</property>

2、在我使用spring mvc 整合hibernate时,代码如下:

<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>



JPA方法:
META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence version="1.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd
http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd"
xmlns:orm="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence">

<persistence-unit name="org.jbpm.persistence.jpa"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
......
<properties>
<property name="hibernate.max_fetch_depth" value="3" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
<property name="hibernate.cache.use_query_cache" value="true"/>
<property name="hibernate.cache.use_second_level_cache" value="true"/>
<property name="hibernate.generate_statistics" value="true"/>
<property name="hibernate.use_sql_comments" value="true"/>
<property name="hibernate.generate_statistics" value="true"/>
</properties>
</persistence-unit>
</persistence>

applicationContext.xml
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="xDataSource" />
<property name="persistenceUnitName" value="org.jbpm.persistence.jpa" />
</bean>


值说明:
validate 加载hibernate时,验证创建数据库表结构
create 每次加载hibernate,重新创建数据库表结构。
create-drop 加载hibernate时创建,退出是删除表结构
update 加载hibernate自动更新数据库结构
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值