Hibernate中自动生成数据库表的两种方式

来源:互联网 发布:阿曼用什么插头 知乎 编辑:程序博客网 时间:2024/04/30 03:41

第一种方式: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以后,数据库中的表就会自动的创建并更新了。
0 0