JPAをスタンドアローンなJava5アプリケーションで使う方法
Java Persistence API (JPA)をスタンドアローンなJava5アプリケーションから使ってみる。JPA実装にはHibernateを利用する。
インストール
HibernateのウェブページからHibernate Core、Hibernate-annotations、Hibernate-entitymanagerをダウンロードし、依存ライブラリと共にダウンロードしたjarにクラスパスを通す。
Persistence unitの定義
最初にPersistence unitを定義する。一つのPersistence unitは一つのデータベース(データソース?)に対応するようだ。
以下のxmlを作成し、persistence.xmlと言う名前でクラスパスの通ったフォルダの下のMETA-INFフォルダに保存する。
<persistence>
<persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
<class>org.hibernate.ejb.test.Cat</class>
<class>org.hibernate.ejb.test.Distributor</class>
<class>org.hibernate.ejb.test.Item</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQL
Dialect"/>
<property name="hibernate.connection.driver_class" value="org.hsqldb
.jdbcDriver"/>
<property name="hibernate.connection.username" value="sa"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url" value="jdbc:hsqldb:."/>
<property name="hibernate.max_fetch_depth" value="3"/>
</properties>
<persistence-unit>
</persistence>
この例では「jdbc:hsqldb:.」というURLのデータベースを利用する「manager1」と言う名前のpersistence unitを定義している。
classタグ内に永続化クラスを指定する。その他hibernateの設定ファイル(*.hbm.xml)を登録する方法もあるようだ。
propertyタグ内はもうそのまんまhibernateの設定。
永続化クラスの定義
アノテーションを使って永続化クラスを定義してやる。
使ってみる
先ほど「manager1」と言う名前のpersistence unitを定義したので、そこに永続化オブジェクトを永続化してみる。
EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Item item = new Item();
item.setProductName("Ahhhh!!!");
item.setQuantity(30);
em.persist(item);
tx.commit();
em.close();
emf.close();
めちゃ簡単。