待实体类及映射文件生成后,进行如下操作:
1、在hibernate.cfg.xml配置文件中配置数据源、表生成属性及映射文件信息
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="myeclipse.connection.profile"> com.mysql.jdbc.Driver </property> <property name="connection.url"> jdbc:mysql://192.0.0.0:3306/databaseName </property> <property name="connection.username">root</property> <property name="connection.password">****</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="show_sql">true</property>
<!-- auto schema export --> <property name="hibernate.hbm2ddl.auto">update</property> <mapping resource="com/prochanges/framework/domain/hbm/Addressbook.hbm.xml" /> <mapping ......
</session-factory>
</hibernate-configuration>
2、编写hbm2ddl工具类,将实体类生成数据库表,运行如下main方法即可
package com.hutton;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class GenerateDatabaseTable
{
/**
* @param args
*/
public static void main(String[] args)
{
//read the config file
Configuration conf = new Configuration().configure();
SchemaExport export = new SchemaExport(conf);
export.create(true, true);
}
}
相关属性信息可参见:
D:\...\hibernate-3.2\etc\hibernate.properties文件
#hibernate.hbm2ddl.auto create-drop 根据你的model类来生成表,但是每次运行都会删除上一次的表,重新生成表,哪怕2次没有任何改变
#hibernate.hbm2ddl.auto create 根据model类生成表,但是sessionFactory一关闭,表就自动删除
#hibernate.hbm2ddl.auto update 最常用的属性,也根据model类生成表,即使表结构改变了,表中的行仍然存在,不会删除以前的行
#hibernate.hbm2ddl.auto validate 只会和数据库中的表进行比较,不会创建新表,但是会插入新值