Spring+HibernateEntityManager(HibernateEntityManager単体編)

おいらはここ数年 Spring Framework と HibernateEntityManager 環境で開発をすることが多いのですが、動けばいいやー的な方向に流されてるような気がする今日この頃です。

ということで、Spring+HibernateEntityManager 環境について、ステップ・バイ・ステップで確認していこうと思います。

概要

HibernateEntityManager を超ベタに使うサンプルです。
一応基本ということで (^^;

例題

  • エンティティ A を保存します。

ソース

エンティティ A

最低限の情報を持つエンティティです。Simple is Best ということで。

package sample;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class A {
    @Id
    @GeneratedValue
    private int id;
}
META-INF/persistence.xml

今回は、hibernate.cfg.xml 等は使わずに、persistence.xml にすべてまとめています。おいら個人的には、このスタイルが好きですねー。

<persistence
  xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
  version="1.0"
>
  <persistence-unit name="manager" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
    
      <!-- データソースの設定 -->
      <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
      <property name="hibernate.connection.username" value="root" />
      <property name="hibernate.connection.password" value="" />
      <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test" />
      <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
      
      <!-- テスト用プログラムなので、毎回DBのテーブルをを新規作成するように設定。 -->
      <property name="hibernate.hbm2ddl.auto" value="create-drop" />
      
    </properties>
  </persistence-unit>
</persistence>
サンプル用のメインクラス
package sample;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class SampleMain {
    
    // A を新規作成し、DB に保存
    public static void main(String[] args) throws Exception {
        
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager");
        // emf は org.hibernate.ejb.EntityManagerFactoryImpl クラス
        
        EntityManager em = emf.createEntityManager();
        // em は org.hibernate.ejb.EntityManagerImpl クラス
        
        EntityTransaction tx = em.getTransaction();
        // tx は org.hibernate.ejb.TransactionImpl クラス
        
        tx.begin();
        // DB : SET autocommit=0
        
        em.persist(new A());
        // DB : insert into A values ( )
        
        tx.commit();
        // DB : commit
        // DB : SET autocommit=1
        
    }
}

参考

サンプル