hibernate自动建表

第一种方式:

hibernate.cfg.xml文件中的hibernate.hbm2ddl.auto 属性配置,如下:

Xml代码  
  1. <!--   
  2.     create:先删除,再创建  
  3.     update:如果表不存在就创建,不一样就更新,一样就什么都不做。  
  4.     create-drop:初始化时创建表,SessionFactory执行close()时删除表。  
  5.     validate:验证表结构是否一致,如果不一致,就抛异常。  
  6. -->  
  7. <property name="hibernate.hbm2ddl.auto">update</property>  

 

第二种方式:

使用hibernate提供的一个工具类。

org.hibernate.tool.hbm2ddl.SchemaExport

用法见如下demo代码:

Java代码  收藏代码
  1. package com.yx.jtest;  
  2.   
  3. import org.hibernate.cfg.Configuration;  
  4. import org.hibernate.tool.hbm2ddl.SchemaExport;  
  5.   
  6. public class Test {  
  7.   
  8.     public static void main(String[] args) {  
  9.         // 根据hibernate核心配置文件生成表结构  
  10.         Configuration cfg = new Configuration();  
  11.         cfg.configure("hibernate.cfg.xml");  
  12.         SchemaExport schemaExport = new SchemaExport(cfg);  
  13.           
  14.         boolean script = true;  
  15.         boolean export = true;  
  16.         /** 
  17.          * 创建表结构 
  18.          * 第一个参数script的作用:print the DDL to the console 
  19.          * 第二个参数export的作用:export the script to the database 
  20.          */  
  21.         schemaExport.create(script, export);  
  22.           
  23.         // drop 表结构  
  24.         // schemaExport.drop(script, export);  
  25.     }  
  26.   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值