SchemaExportでHibernateマッピングファイルからDBスキーマの作成

2009/03/09 18:02Update
TAGS: hibernate | SchemaExport | マッピング | hibernate.cfg.xml | SQL | DB | スキーマ | テーブル | hbm2ddl | DDL

Hibernate SchemaExportクラスを利用してHibernateマッピングファイルからSQL文やDBスキーマの作成するサンプルです。

コード
Hbm2DDL.java
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;

public class Hbm2DDL {

    /**
     * @param args
     */
    public static void main(String[] args) {
        genernate("hibernate.cfg.xml", "c:\\mydb.sql", true, true);
    }


    /**
     * Hibernateの設定ファイルからDDL生成(テーブル作成)
     * @param hibernateCfgXml hibernate.cfg.xmlのパス。null可
     * @param sqlPath SQL文を格納するファイル・パス
     * @param export2db DBにテーブルを生成
     * @param dropddl ドロップDDLを生成するかどうか
     * @return true/false
     */
    public static boolean genernate(String hibernateCfgXml, String sqlPath, boolean export2db, boolean dropddl) {
        System.out.println("DDLCodegen.genernate() start.");
        
        Session session;
        Configuration config = null;
        Transaction tx = null;
        
        try {
            
            if (hibernateCfgXml == null || hibernateCfgXml.equals("")) {
                config = new Configuration().configure();
            } else {
                try {
                    config = new Configuration().configure(new File(hibernateCfgXml));
                } catch (Exception e) {
                    config = new Configuration().configure(hibernateCfgXml);
                }
            }

            SessionFactory sessionFactory = config.buildSessionFactory();
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
            
            SchemaExport schemaExport = new SchemaExport(config);
            
            if (sqlPath != null && !sqlPath.equals("")) {
                schemaExport.setOutputFile(sqlPath);
            }
            
            schemaExport.create(true, export2db);
            if (dropddl) {
                schemaExport.drop(true, export2db);
            }

            tx.commit();
            
        } catch (HibernateException e) {
            e.printStackTrace();
            try {
                tx.rollback();            
            } catch (HibernateException e1) {
                e1.printStackTrace();
            }
        } finally {
            
        }
        
        System.out.println("DDLCodegen.genernate() end.");
        
        return true;
    }
}


SchemaExportをJavaコードから利用するほか、コマンドラインやAntタスクなどからも簡単に利用できます。詳細は、次の記事をご参照ください。
第20章 Toolset Guide ツールセットガイド - Hibernateリファレンス

有关作者
Syboos.jp編集長AJavaやオープンソース情報の執筆、Webサイトの開発や運営全般の業務に携わる。

Sponsored Link


Comments