首页 > Web开发 > 详细

hibernate自动创建表结构的两种方式

时间:2015-09-04 02:27:53      阅读:437      评论:0      收藏:0      [点我收藏+]

第一种方式:

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

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

?

第二种方式:

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

org.hibernate.tool.hbm2ddl.SchemaExport

用法见如下demo代码:

package com.yx.jtest;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class Test {

	public static void main(String[] args) {
		// 根据hibernate核心配置文件生成表结构
		Configuration cfg = new Configuration();
		cfg.configure("hibernate.cfg.xml");
		SchemaExport schemaExport = new SchemaExport(cfg);
		
		boolean script = true;
		boolean export = true;
		/**
		 * 创建表结构
		 * 第一个参数script的作用:print the DDL to the console
		 * 第二个参数export的作用:export the script to the database
		 */
		schemaExport.create(script, export);
		
		// drop 表结构
		// schemaExport.drop(script, export);
	}

}

?SchemaExport的更多用法,可以去看源码或java doc

?

hibernate自动创建表结构的两种方式

原文:http://xigua366.iteye.com/blog/2240466

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!