Hibernate中自动生成数据库表的两种方式
生活随笔
收集整理的這篇文章主要介紹了
Hibernate中自动生成数据库表的两种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一種方式:Hibernate中利用工具類自動生成數據庫表
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();?
? ?? ???//創建SchemaExport對象?
? ?? ???SchemaExport export = new SchemaExport(cfg);?
? ?? ???//創建數據庫表?
? ?? ???export.create(true,true);?
? ? }?
}
復制代碼
3.運行工具類生成表。
第二種方式:
通過設置hibernate.cfg.xml自動生成數據庫表 hbm2ddl 參見hibernate解壓文件etc文件夾中hibernate.property 的說明然后,啟動Tomcat就可以創建數據庫表。???
創建過程分析:???
在hibernate.cfg.xml中配置相應的數據庫驅動和連接,并設置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>? ?? ?
復制代碼
當tomcat啟動的時候,就會通過web.xml加載spring中的applicationContext*.xml的配置文件,在applicationContext*.xml中會有相應的SessionFactory的配置,具體如下:???
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">? ?? ?? ??
<property name="configLocation">? ?? ?? ?? ???
<value>classpath:hibernate.cfg.xml</value>? ?? ?? ??
</property>? ?? ?
</bean>? ?? ?
復制代碼
這樣加載了sessionFactory以后,數據庫中的表就會自動的創建并更新了。
總結
以上是生活随笔為你收集整理的Hibernate中自动生成数据库表的两种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用hibernate自动生成数据库表
- 下一篇: 利用Eclipse/MyEclipse