`

Hibernate_自动创建表的方法

 
阅读更多

有两种方法:

一:在配置文件中加上 <property name="hibernate.hbm2ddl.auto">create</property>

这个语句,然后我们再执行任何检索、更新等操作的时候就会自动建表

 

hibernate.hbm2ddl.auto Automatically validate or export schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly. eg. validate | update | create | create-drop

 

其实这个参数的作用主要用于:自动创建|更新|验证数据库表结构。

如果没有此方面的需求建议set value="none".

 

其它几个参数的意思:

validate               加载hibernate时,验证创建数据库表结构

create                  每次加载hibernate,重新创建数据库表结构(如果表存在,先删除再创建,原有数据丢失)

create-drop        加载hibernate时创建,退出时删除表结构

update                 加载hibernate自动更新数据库结构(schema发生改变时进行更新,比如添加字段,保留原有数据)

如果发现数据库表丢失或新增,请检查hibernate.hbm2ddl.auto的配置 可设置 <property name="hibernate.hbm2ddl.auto" value="none" />

建议在开发环境下使用,在生产环境下去掉。

 

优点:

1、自动创建新表

2、自动创建新字段

3、自动修改字段类型

 

缺点:

1、不会自动删除表

2、不会自动删除字段

3、自动创建的新字段只能是在最后。

 

 

二: 编写一个方法,方法内容如下:

  Configuration conf=new Configuration();

  conf.configure("/hibernate.cfg.xml");

  SchemaExport dbExport=new SchemaExport(conf);

  dbExport.create(true, true);

注意: .cfg.xml文件中dialect必须配置正确,才能正确创建表

<property name="dialect">org.hibernate.dialect.HSQLDialect</property><!-- cannot create table -->

<property name="dialect">org.hibernate.dialect.MySQLDialect</property><!-- OK -->

 

ps:建议仅在练习中如上述方法创建。因为存在以下问题:

1:只能创建表不能创建数据库

2:创建的表的数据类型、长度经常跟我们实际需要不符。

4:缺少初始化数据。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics