詳解hibernate自動(dòng)創(chuàng)建表的配置
配置自動(dòng)創(chuàng)建表:
<prop key="hibernate.hbm2ddl.auto">update</prop>//首次創(chuàng)建項(xiàng)目時(shí)用,項(xiàng)目穩(wěn)定后一般注釋這里有4個(gè)值:
update:表示自動(dòng)根據(jù)model對(duì)象來更新表結(jié)構(gòu),啟動(dòng)hibernate時(shí)會(huì)自動(dòng)檢查數(shù)據(jù)庫,如果缺少表,則自動(dòng)建表;如果表里缺少列,則自動(dòng)添加列。
還有其他的參數(shù):
create:啟動(dòng)hibernate時(shí),自動(dòng)刪除原來的表,新建所有的表,所以每次啟動(dòng)后的以前數(shù)據(jù)都會(huì)丟失。
create-drop:啟動(dòng)hibernate時(shí),自動(dòng)創(chuàng)建表,程序關(guān)閉時(shí),自動(dòng)把相應(yīng)的表都刪除。所以程序結(jié)束時(shí),表和數(shù)據(jù)也不會(huì)再存在。
validate :
每次加載hibernate時(shí),驗(yàn)證創(chuàng)建數(shù)據(jù)庫表結(jié)構(gòu),只會(huì)和數(shù)據(jù)庫中的表進(jìn)行比較,不會(huì)創(chuàng)建新表,但是會(huì)插入新值。
然后在配置 讀取實(shí)體類映射:
有3種方法:
1、(常用)通過注解掃描包的方式:
<property name="packagesToScan"><list><value>com.systop.common.core.dao.testmodel</value></list>
2、通過注解的方式:
<property name="annotatedClasses"> <list><value>com.systop.common.core.dao.testmodel.TestDept</value></list> </property>
3、mappingResources用于指定少量的hibernate配置文件像這樣
Xml代碼
<property name="mappingResources"> <list> <value>WEB-INF/conf/hibernate/cat.hbm.</value> <value>WEB-INF/conf/hibernate/dog.hbm.xml</value> ...... </list> </property>
實(shí)例:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:/dataSource/jdbc.properties</value> </list> </property></bean><!-- 配置數(shù)據(jù)源 --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${jdbcCcbs.driverClassName}"/> <property name="url" value="${jdbcCcbs.url}"/> <property name="username" value="${jdbcCcbs.username}"/> <property name="password" value="${jdbcCcbs.password}"/></bean><!-- 配置SessionFactory--><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><!--<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">--> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <!--自動(dòng)創(chuàng)建表配置--> <!--<prop key="hibernate.hbm2ddl.auto">update</prop>--> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <!--結(jié)果滾動(dòng)集,跟分頁有關(guān)--> <prop key="jdbc.use_scrollable_resultset">false</prop> </props> </property> <!--<property name="annotatedClasses">--> <!--<list>--> <!--<value>com.jason.entity.UserEntity</value>--> <!--</list>--> <!--</property>--> <property name="packagesToScan"> <list> <value>com.jason.entity</value> </list> </property></bean>感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選