Java > マッピングファイルからJavaクラス生成
更新日
2012-08-22
広告
Hibernateを使い、マッピングファイルからJavaクラスやRDBのテーブルを作成する方法を紹介します。Eclipseプラグインを使う方法が主流のようですが、いちいちEclipseを使いたくないのでantを使う方法を紹介します。
参考サイト
- http://www.redhat.com/developer_studio/guides/hibernatetools/html_single/
- http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html/ch01.html
ライブラリの準備
antからHibernateを利用するためには、Hibernate toolsが必要です。Hibernate toolsは、JBoss toolsの一部として提供されています。今回は、jbosstools-3.3.1.Final.component--hibernatetools-Update-2012-07-14_23-57-15-H211.zip を使います。このファイルは、JBoss Toolsのダウンロードサイトからダウンロードできます。
ダウンロードしたzipファイルを解凍すると、pluginディレクトリが生成されます。pluginディレクトリ以下のorg.hibernate.eclipse.libs_3.5.1.v20120715-0252-H98-Final.jarを解凍します。
$ jar xvf org.hibernate.eclipse.libs_3.5.1.v20120715-0252-H98-Final.jar解凍すると lib ディレクトリが作成されます。その下に、色々なjarファイルがあります。以降、これらのjarファイルを全部使うので、てきとうなディレクトリに全部コピーします。今回は、lib というディレクトリを作成し、そこに全部コピーします。
また、MySQLのJDBCドライバも用意しておきます。今回は mysql-connector-java-5.0.jar を使います。
Javaクラスの生成
Hibernateのマッピングファイル Event.hbm.xml を作成します。
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="Event" table="EVENTS"> <id name="id" column="EVENT_ID" type="long"> <generator class="native"/> </id> <!-- name属性はJavaクラスの変数名、column属性はテーブルのカラム名 --> <property name="date" type="timestamp" column="EVENT_DATE"/> <!-- name属性だけだと、カラム名もname属性の値が適用される --> <property name="title" type="string"/> <property name="enabled" type="boolean"/> </class> </hibernate-mapping>Event.hbm.xmlの配置場所は、パッケージ名に合わせてください。今回の場合だと、org/hibernate/tutorial/domain/ディレクトリ以下に配置します。
また、Hibernateのコンフィグファイル hibernate.cfg.xml を作成します。
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///hibernate_test</property> <property name="connection.username">root</property> <property name="connection.password">hogehoge</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <!-- <property name="hbm2ddl.auto">update</property> --> <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> </session-factory> </hibernate-configuration>この段階では、重要なのは後半の mapping 要素です。ここで、先ほど作成した Event.hbm.xml を指定してください。
次に、build.xmlを作成します。
<project name="test" default="gen" basedir="."> <path id="toolslib"> <fileset dir="lib"> <include name="**/*.jar"/> </fileset> </path> <taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="toolslib" /> <target name="gen"> <hibernatetool destdir="generated"> <!-- Event.hbm.xmlを見つけるためにパスを通す --> <classpath> <pathelement location="."/> </classpath> <configuration configurationfile="hibernate.cfg.xml"/> <!-- Javaクラス生成 --> <hbm2java/> </hibernatetool> </target> </project>path要素内のfileset内で、明示的に Event.hbm.xml を指定すると、以下のエラーが発生する場合があるので注意してください。これは、antが、Event.hbm.xmlをjarファイルだと勘違いするためです。
java.util.zip.ZipException: error in opening zip file
antを実行すると、クラス Event.java が生成されます。
package org.hibernate.tutorial.domain; // Generated 2012/08/22 0:32:44 by Hibernate Tools 3.4.0.CR1 import java.util.Date; /** * Event generated by hbm2java */ public class Event implements java.io.Serializable { private long id; private Date date; private String title; public Event() { } public Event(Date date, String title) { this.date = date; this.title = title; } public long getId() { return this.id; } public void setId(long id) { this.id = id; } public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } }マッピングファイルを更新して、antを実行すると、Javaクラスは自動的に更新されます。
ちなみに、build.xmlに <hbm2dao/> を追加すると、DAOクラスも生成してくれます。
<target name="gen"> <hibernatetool destdir="generated"> <!-- Event.hbm.xmlを見つけるためにパスを通す --> <classpath> <pathelement location="."/> </classpath> <configuration configurationfile="hibernate.cfg.xml"/> <!-- POJOの生成 --> <hbm2java/> <!-- DAOの生成 --> <hbm2dao/> </hibernatetool> </target>
テーブルの生成
マッピングファイルから、RDBのテーブルを作成できます。今回は、MySQLサーバに「ユーザroot」「パスワードhogehoge」でログインできる環境を用意します。また、MySQLに hibernate_test というデータベースを作成しておきます。RDB関連の設定は hibrenate.cfg.xml の以下の部分で行います。
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///hibernate_test</property> <property name="connection.username">root</property> <property name="connection.password">hogehoge</property>
テーブルを作るには、build.xmlに <hbm2ddl/> を追加するだけでOKです。
<target name="gen"> <hibernatetool destdir="generated"> <!-- Event.hbm.xmlを見つけるためにパスを通す --> <classpath> <pathelement location="."/> </classpath> <configuration configurationfile="hibernate.cfg.xml"/> <!-- POJOの生成 --> <hbm2java/> <!-- テーブルの生成 --> <hbm2ddl/> </hibernatetool> </target>
antを実行すると、以下のログが出力されます。
$ ant [hibernatetool] 1. task: hbm2java (Generates a set of .java files) : [hibernatetool] 2. task: hbm2ddl (Generates database schema) [hibernatetool] create table EVENTS (EVENT_ID bigint not null auto_increment, EVENT_DATE datetime, title varchar(255), primary key (EVENT_ID));テーブルの作成処理が行われていることがわかります。MySQLで確認してみます。
mysql> use hibernate_test; Database changed mysql> show tables; +--------------------------+ | Tables_in_hibernate_test | +--------------------------+ | EVENTS | +--------------------------+ 1 row in set (0.01 sec) mysql> describe EVENTS; +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | EVENT_ID | bigint(20) | NO | PRI | NULL | auto_increment | | EVENT_DATE | datetime | YES | | NULL | | | title | varchar(255) | YES | | NULL | | +------------+--------------+------+-----+---------+----------------+ 3 rows in set (0.04 sec)mappingファイルを変更した場合は、一度テーブルを削除してから ant を実行しないと、テーブルは更新されません。わざわざテーブルを削除するのが面倒な場合は、build.xmlにて hbm2ddlにupdate属性を追加するとよいです。
<hbm2ddl update="true" ...ただし、テーブルにデータが入っていても自動的に削除されて、テーブルが更新されるので、注意してください!
広告
お問い合わせは sweng.tips@gmail.com まで。