第一种方式:
配置 hibernate.cfg.xml
修改文件中的hibernate.hbm2ddl.auto 属性配置:
Xml代码
- <!--
- create:先删除,再创建
- update:如果表不存在就创建,不一样就更新,一样就什么都不做。
- create-drop:初始化时创建表,SessionFactory执行close()时删除表。
- validate:验证表结构是否一致,如果不一致,就抛异常。
- -->
- <property name="hibernate.hbm2ddl.auto">update</property>
第二种方式:
在配置文件hibernate.cfg.xml配置映射关系
<mapping resource="com/test/entity/UserData.hbm.xml" />
使用hibernate提供的一个工具类。
org.hibernate.tool.hbm2ddl.SchemaExport
Java代码
- public class TableTest{
- 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);
- }
- }