ぺーぺーSEのブログ

備忘録・メモ用サイト。

Hibernateを使ってみる(JPAを使って)

データベース製品の多様性を隠ぺいするためにJDBCが考えられたように、あるいはMOM製品の多様性を隠ぺいするためにJMSというAPIが考えらた。
JPAはO/Rマッパーの違いを隠ぺいするためのAPIである。

プロジェクト作成に下記を実行。

mvn archetype:generate -DgroupId=study 
                       -DartifactId=HibernateJpaSample 
                       -DarchetypeArtifactId=maven-archetype-quickstart 
                       -Dversion=1.0.0

POMを修正

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>study</groupId>
  <artifactId>HibernateJpaSample</artifactId>
  <packaging>jar</packaging>
  <version>1.0.0</version>
  <name>HibernateJpaSample</name>
  <url>http://maven.apache.org</url>

  <build>
    <testResources>
      <testResource>
        <filtering>false</filtering>
        <directory>src/test/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </testResource>
      <testResource>
        <directory>src/test/resources</directory>
      </testResource>
    </testResources>
  </build>

  <dependencies>
    <!-- JPAを使用する際に必要 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.1.4.Final</version>
    </dependency>

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

    <!-- Hibernate uses jboss-logging for logging, for the tutorials we will
      use the sl4fj-simple backend -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.6.1</version>
    </dependency>

    <!-- The tutorials use JUnit test cases to illustrate usage -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
    </dependency>

    <!-- The tutorials use the H2 in-memory database -->
    <dependency>
      <groupId>postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>9.1-901.jdbc4</version>
    </dependency>
  </dependencies>
</project>

設定ファイルは
hibernate.cfg.xml
は不要!!
Mavenプロジェクト構造のjava/main/resources直下に
「META-INF/persistence.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_2_0.xsd"
  version="2.0">

  <persistence-unit name="jp.sample.jpa">
    <description>
            Persistence unit for the JPA sample of the Hibernate
        </description>

    <class>jp.sample.vo.Book</class>

    <properties>
      <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
      <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/test" />
      <property name="javax.persistence.jdbc.user" value="postgres" />
      <property name="javax.persistence.jdbc.password" value="xxxxxx" />
      <property name="hibernate.show_sql" value="true" />
      <property name="hibernate.hbm2ddl.auto" value="create" />
    </properties>

  </persistence-unit>
</persistence>
  • persistence-unit要素
      • name属性
        • プログラムから呼び出すpersistence-unitの名前を定義する。

■Book.java

package jp.sample.vo;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table( name = "BOOK" )
public class Book {

	private Long isbn;
	private String title;
	private Date date;

	public Book() {

	}

	public Book(String title, Date date) {
		this.title = title;
		this.date = date;
	}

	@Id
	@GeneratedValue(generator="increment")
	@GenericGenerator(name="increment", strategy = "increment")
	public Long getIsbn() {
		return isbn;
	}

		public void setIsbn(Long isbn) {
		this.isbn = isbn;
	}

		public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "date")
	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
}

実行するメインクラス。

■Main.java

package jp.sample.main;

import java.util.Date;
import java.util.List;

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

import jp.sample.vo.Book;

public class Main {

	public static void main(String[] args) {

		// EntitiyManagerFactoryでpersistence.xmlのpersistence-unit要素の設定を読み込み
		EntityManagerFactory entityManagerFactory
				= Persistence.createEntityManagerFactory("jp.sample.jpa");

		// EntitiyManagerFactoryからEntitiyManagerを生成
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
		entityManager.persist(new Book("Hibernate", new Date()));
		entityManager.persist(new Book("JPA", new Date()));
		entityManager.getTransaction().commit();
		entityManager.close();

		// now lets pull events from the database and list them
		entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
		List<Book> result = entityManager.createQuery("from jp.sample.vo.Book",
				Book.class).getResultList();
		for (Book event : result) {
			System.out.println("Book (" + event.getDate() + ") : "
					+ event.getTitle());
		}
		entityManager.getTransaction().commit();
		entityManager.close();

		entityManagerFactory.close();
	}
}

PostgreSQL9.1に下記でテーブル作成。

create table BOOK (
  isbn   integer  primary key,
  title  varchar,
  date   timestamp
);

参考
http://www.hibernate.org/
http://codezine.jp/article/detail/5061