Hibernateでソースコードからスキーマを生成する方法
Hibernateには作成したマッピングファイルから、 テーブルを生成する方法があります。
大体の本ではマッピングファイルを用意した後に、 antやコマンドから自動でデータベースにテーブルを生成する方法は書いてあるのですが、ソースコードから同じことをする方法が書いてない。
これだと作ったアプリケーションをインストールする前に、 インストーラかもしくは管理者がデータベース上にアプリケーションから使用するテーブルを作っておかなければならない。
普通のシステムとかだったら既存のデータベースに接続するプログラムとかだと思うので、アプリケーションから作成する必要はないのでしょうけど、 組み込みデータベースを使用したアプリケーションだとそうもいかない。 (まあ最初から接続するデータベースをアプリケーションにデータごと保存して置けばいいのですが。。)
と言うわけで調べてみました。
antからテーブルを生成する際に使用するタスクは、
net.sf.hibernate.tool.hbm2ddl.SchemaExportTask
。
ちゅうことでこのクラスのexecuteメソッドを調べてみると。。。
/**
* Execute the task
*/
public void execute() throws BuildException {
try {
Configuration cfg = getConfiguration();
SchemaExport schemaExport = getSchemaExport(cfg);
if (drop) {
schemaExport.drop(!quiet, !text);
} else {
schemaExport.create(!quiet, !text);
}
} catch (HibernateException e) {
throw new BuildException("Schema text failed: "
+ e.getMessage(), e);
} catch (FileNotFoundException e) {
throw new BuildException("File not found: "
+ e.getMessage(), e);
} catch (IOException e) {
throw new BuildException("IOException : "
+ e.getMessage(), e);
} catch (Exception e) {
throw new BuildException(e);
}
}
一目瞭然。
net.sf.hibernate.tool.hbm2ddl.SchemaExport#create()
を使えばよいと言うことが判った。
SpringFrameworkとHibernateを連携させている場合にはorg.springframework.orm.hibernate.LocalSessionFactoryBean#createDatabaseSchema()
を使えばよさそう。