使用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的方式省略。