关于Spring整合Hibernate中自动建表

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自动更新数据库结构

你可能感兴趣的:(Hibernate)