目前很多人使用Hibernate作为持久层,如果我们已经写了配置文件poweracl.hbm.xml,则不必再费劲写SQL的DDL。除了利用工具SchemaExport之外,还可以编写程序来自动初始化数据库(数据库培训 数据库认证 ),并且生成SQL DDL。
(1)Hibernate配置文件hibernate.cfg.xml
com.mysql.jdbc.Driver
jdbc:mysql://localhost/hibtest
test
123456
20
true
50
25
false
net.sf.hibernate.dialect.MySQLDialect
注意:(1)JDBC驱动为com.mysql.jdbc.Driver,可以根据所使用的库而更换。
(2)dialect为数据库方言,根据所使用数据库不同而不同。这里是Mysql。
(3)jdbc.fetch_size和jdbc.batch_size过小会降低性能,这里是建议设置。
(4)mapping文件根据文件所在路径而不同。这里是放在WEB-INF/classes/com/hibtest/目录下。
(2)数据库映射配置poweracl.hbm.xml
说明:具体的poweracl.hbm.xml要根据数据库表而设置,这里只是列举一个user表。
(3) 初始化数据库类
package com.hibtest;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
/**
*
vedadou
* Date: 2004-02-25
* Time: 9:40:15
*/
public class InitDB {
static Session session;
public static void main(String[] args) {
Configuration config = null;
Transaction tx = null;
try {
config = new Configuration().configure(new File("hibernate.cfg.xml"));
System.out.println("Creating tables...");
SchemaExport schemaExport = new SchemaExport(config);
schemaExport.create(true, true);
System.out.println("Table created.");
SessionFactory sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();
tx = session.beginTransaction();
tx.commit();
} catch (HibernateException e) {
e.printStackTrace();
try {
tx.rollback();
} catch (HibernateException e1) {
e1.printStackTrace();
}
} finally {
}
}
}
注意:在初始化之前,应该先手工创建一个空数据库,然后再执行InitDB程序
(责任编辑:代君利) |