使用Hibernate生成数据表的两种方式

1.建好POJO object, XML Mapping File,配置文件(hibernate.cfg.xml).

 

2.编写工具类

i mport 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值