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

第一种方式:

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

猜你喜欢

转载自xigua366.iteye.com/blog/2240466