Hibernate使用hbm2ddl创建或更新数据库表

来源:互联网 发布:网络管理规范 编辑:程序博客网 时间:2024/06/05 06:56

使用hibernate自带的hbm2ddl可以实现自动创建和更新数据库表。使用起来也很简单。

 

只需要在hibernate-config.xml配置文件中设置:

 <property name="hbm2ddl.auto">create</property>

 

文档中是如下注解:

SessionFactory创建时,自动检查数据库结构,或者将数据库schema的DDL导出到数据库. 使用 create-drop时,在显式关闭SessionFactory时,将drop掉数据库schema.

取值 validate | update | create | create-drop

 

程序就会自动创建或更新表。

 

 

也可以手动调用create方法,将sql语句导出,让其自动在数据中执行。

 

hbm2ddl包的位置:org.hibernate.tool.hbm2ddl;

 

其中有一个重要的类:SchemaExport

 

create方法的参数如下。

 

 /**
  * Run the schema creation script.
  *
  * @param script print the DDL to the console
  * @param export export the script to the database
  */
 public void create(boolean script, boolean export) {
  execute( script, export, false, false );
 }

 

 

 PS:如果有many to one,默认生成的字段名是 关联表的表名_主键(假设为主键关联)

 

 如果想自己设置关联的字段名,可以加 @JoinColumn(name="roleid")-----Annotation的方法。xml的方式省略。

原创粉丝点击