Hibernate自动建表

来源:互联网 发布:政治敏感 知乎 编辑:程序博客网 时间:2024/05/17 17:15

Hibernate自动建表


方法一:在hibernate.cfg.xml中通过配置自动建表



<property name="hibernate.hbm2ddl.auto">create-drop</property>

每次在创建sessionFactory时候执行创建表;

当调用sesisonFactory的close方法的时候,删除表!

 <property name="hibernate.hbm2ddl.auto">create</property> 每次都重新建表; 如果表已经存在就先删除再创建

<property name="hibernate.hbm2ddl.auto">update</property>  如果表不存在就创建; 表存在就不创建;

 <property name="hibernate.hbm2ddl.auto">validate</property>  (生成环境时候) 执行验证: 当映射文件的内容与数据库表结构不一样的时候就报错!


注意:创建表之后在表中进行拆入数据时id值也要设置,不然为0,重复执行时,无法实现自增长。


方法二:代码自动建表

public class App_ddl {// 自动建表@Testpublic void testCreate() throws Exception {// 创建配置管理类对象Configuration config = new Configuration();// 加载主配置文件config.configure();// 创建工具类对象SchemaExport export = new SchemaExport(config);// 建表// 第一个参数: 是否在控制台打印建表语句// 第二个参数: 是否执行脚本export.create(true, true);}}





原创粉丝点击