---
title: "关于hibernate的自动建表、"
author: "lyuno"
date: "2011-05-05T21:04:25Z"
tags: []
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2011-05-05T21:05:58Z"
id: 1032289
url: "https://lyuno.iteye.com/blog/1032289"
---

虽然用hibernate来帮助建表、这种做法有点非主流、但是还是懂多点好！
让hibernate自动建表有两种方法、第一种：直接配置hibernate.cfg.xml配置文件、
第二种、就是像下面这样、写个建表类！我个人觉得、还是写个建表类好！
因为表是创建一次就可以的了！如果用了配置文件的话、配置属性：


```java
<property name="hibernate.hbm2ddl.auto">create</property>
```


这样的话！你运行一次之后、你不改成update、或者none的话、它就会在每运行一次、就创建一次表！

所以、以下方法比较为优

```java
package com.juno.util;

import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class CreateTable {

	public static void main(String[] args) {
		Configuration cfg = new Configuration();
		// 这个一定要加、读者哪个文件来帮助创建表
		cfg.configure("/hibernate.cfg.xml");
		SchemaExport export = new SchemaExport(cfg);
		// 删除一个表的语句：drop
		// export.drop(true, true);

		// 创建一个表的语句
		export.create(true, true);
	}
}

```