利用Hibernate的配置反向生成数据库

阅读更多
利用Hibernate配置文件生成数据库


转载自:http://tzylwl.iteye.com/blog/1153626

目前很多人使用Hibernate作为持久层,如果我们已经写了配置文件poweracl.hbm.xml,则不必再费劲写SQL的DDL。除了利用工具 SchemaExport之外,还可以编写程序来自动初始化数据库,并且生成SQL DDL。
1.Hibernate配置 文件hibernate.cfg.xml


          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">



   
       
       true
      
       true
        root
        jdbc:mysql://localhost:3306/hibtest
        org.hibernate.dialect.MySQLDialect
        netjava
        com.mysql.jdbc.Driver
    
 
       
      
   


注意:(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



  (2)

  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">



   
      
          
          
      

      
          
      

      
          
      

      
          
      

      
            
      

      
            
      

      
                 
      

   

  
说明:具体的poweracl.hbm.xml要根据数据库表而设置,这里只是列举一个user表。

3.初始化数据库类

package com.hibtest;

import java.io.File;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

/**//**
*

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("E:/javaWeb2/yiwu/WebRoot/WEB-INF/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 {
     
       }
       }
     
}

你可能感兴趣的:(hibernate)