Hibernate中自动生成数据库表的两种方式
生活随笔
收集整理的這篇文章主要介紹了
Hibernate中自动生成数据库表的两种方式
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第一種方式:Hibernate中利用工具類自動(dòng)生成數(shù)據(jù)庫表
1.建好POJO object, XML Mapping File,配置文件(hibernate.cfg.xml).
2.編寫工具類
import org.hibernate.cfg.Configuration;?
import org.hibernate.tool.hbm2ddl.SchemaExport;?
public class ExportDB {?
? ? public static void main(String[] args) {?
? ?? ???//讀取配置文件?
? ?? ???Configuration cfg = new Configuration().configure();?
? ?? ???//創(chuàng)建SchemaExport對象?
? ?? ???SchemaExport export = new SchemaExport(cfg);?
? ?? ???//創(chuàng)建數(shù)據(jù)庫表?
? ?? ???export.create(true,true);?
? ? }?
}
復(fù)制代碼
3.運(yùn)行工具類生成表。
第二種方式:
通過設(shè)置hibernate.cfg.xml自動(dòng)生成數(shù)據(jù)庫表 hbm2ddl 參見hibernate解壓文件etc文件夾中hibernate.property 的說明然后,啟動(dòng)Tomcat就可以創(chuàng)建數(shù)據(jù)庫表。???
創(chuàng)建過程分析:???
在hibernate.cfg.xml中配置相應(yīng)的數(shù)據(jù)庫驅(qū)動(dòng)和連接,并設(shè)置hbm2ddl為update,在web.xml中配置???
spring listener,如下:???
<context-param>? ?? ?? ??
<param-name>contextConfigLocation</param-name>? ?? ?? ??
<param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>? ??
</context-param>? ?? ?
<listener>? ?? ?? ??
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>? ?? ?
復(fù)制代碼
當(dāng)tomcat啟動(dòng)的時(shí)候,就會通過web.xml加載spring中的applicationContext*.xml的配置文件,在applicationContext*.xml中會有相應(yīng)的SessionFactory的配置,具體如下:???
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">? ?? ?? ??
<property name="configLocation">? ?? ?? ?? ???
<value>classpath:hibernate.cfg.xml</value>? ?? ?? ??
</property>? ?? ?
</bean>? ?? ?
復(fù)制代碼
這樣加載了sessionFactory以后,數(shù)據(jù)庫中的表就會自動(dòng)的創(chuàng)建并更新了。
總結(jié)
以上是生活随笔為你收集整理的Hibernate中自动生成数据库表的两种方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用hibernate自动生成数据库表
- 下一篇: myeclipse 2015 stabl