kagamihogeの日記

kagamihogeの日記です。

Hibernateを動かした

http://www.hibernate.org/

なぜにイマサラHibernateかっていうと特に意味は無く。

こんな環境でやりました

  • jdk1.6.0_24
  • eclipse3.7
  • Oracle Database 11g Express Edition(XE)
  • hibernate-core-4.0.0.Final
  • hibernate-entitymanager-4.0.0.Final

Hibernate

まずpom.xmlに追加。今回も最新版ぽいものを使うということで、Sonatype Nexus Professionalで適当に探す。JBoss Maven repositoryの設定も必要だけど省略。※ココなどを参照。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.0.0.Final</version>
</dependency>

クラスパス通ってるディレクトリに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>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="connection.username">kagamihoge</property>
        <property name="connection.password">xxxxxxxxxx</property>
        <property name="connection.pool_size">1</property>
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Names the annotated entity class -->
        <mapping class="entity.Employee"/>

    </session-factory>

</hibernate-configuration>

hibernate.dialectはOracle11gDialect的なものが居ないのでとりあえずナシ。

あと、oracle用のJDBCドライバを適当なとことから持ってきてクラスパスに入れておく。

Java側のソースコード。エンティティのコードは省略。

    private SessionFactory sessionFactory;
    
    @Before
    public void setUp() throws Exception {
        Configuration configure = new Configuration().configure();
        sessionFactory = configure.buildSessionFactory();
    }

    @After
    public void tearDown() throws Exception {
        sessionFactory.close();
    }

    @Test
    public void test() {
        Session session = sessionFactory.openSession();
        try {
            List<Employee> list = session.createCriteria(Employee.class).list()
            for (Employee employee : list) {
                System.out.println(employee.getEmployeeId());
            }
        } finally {
            session.close();
        }
    }

AnnotationConfigurationはめでたく(?)Deprecatedになり、Configurationに統合された模様。
でも設定ファイルでエンティティのmapping指定は必要なのか……
configure()は、中でconfigure( "/hibernate.cfg.xml" );している。ので、↑のサンプルではxmlを明示してないけど、クラスパスにあるhibernate.cfg.xmlを使うようになっている。

buildSessionFactory()がdeprecatedになっているが、一応動くには動く。javadocにはbuildSessionFactory(ServiceRegistry)を使えと書いてあるが、ServiceRegistryの作り方、コレガワカラナイ。

JPA -> Hibernate

JPA経由でHibernateを使う。Hibernateのサイトのトップページに概念図があるんですが。↓の真ん中のJava SE 5.0の右側の方ですね。


何はともあれpom.xmlに追加。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.0.0.Final</version>
</dependency>

クラスパス通ってるディレクトリに、META-INF/persistence.xmlを作成。チュートリアルからコピってきて、oracle向けにちょろっと変えただけです。persistence-unitくらいは変えればよかっただろうか……

<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_2_0.xsd"
             version="2.0">

    <persistence-unit name="org.hibernate.tutorial.jpa">
        <description>
            Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
        </description>
        
        <properties>
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.driver.OracleDriver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:xe" />
            <property name="javax.persistence.jdbc.user" value="kagamihoge" />
            <property name="javax.persistence.jdbc.password" value="xxxxx" />

            <property name="hibernate.show_sql" value="true" />
        </properties>

    </persistence-unit>

</persistence>

内部はHibernateなんで、hibernate.show_sqlとかのプロパティ使えるのがミソなんですかねぇ?

Java側のソースコード

    private EntityManagerFactory factory;
    @Before
    public void setUp() throws Exception {
        factory = Persistence.createEntityManagerFactory("org.hibernate.tutorial.jpa");
    }

    @After
    public void tearDown() throws Exception {
        factory.close();
    }

    @Test
    public void test() {
        EntityManager entityManager = factory.createEntityManager();
        try {
            List<Employee> resultList = entityManager.createQuery("from Employee").getResultList();
            for (Employee employee : resultList) {
                System.out.println(employee.getEmployeeId());
            }
        } finally {
            entityManager.close();
        }
    }

persistence.xmlentity.Employeeとか無くても動くんだけどそーいうもんなんすかね。

一応、こんなキャストも出来る。JPAの意味が無くなってしまうとは思うが……

import org.hibernate.ejb.HibernateQuery;

HibernateQuery createQuery = (HibernateQuery)entityManager.createQuery("from Employee");