ぺーぺーSEのブログ

備忘録・メモ用サイト。

Hibernateを使ってみる

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

mvn archetype:generate -DgroupId=study 
                       -DartifactId=HibernateBasicSample 
                       -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>HibernateBasicSample</artifactId>
  <packaging>jar</packaging>
  <version>1.0.0</version>
  <name>HibernateBasicSample</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>
    <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直下に置いた。
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">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://localhost:5432/test</property>
    <property name="connection.username">postgres</property>
    <property name="connection.password">xxxxxx</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</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">create</property>

    <mapping resource="Book.hbm.xml" />
  </session-factory>
</hibernate-configuration>
  • mapping要素
      • resource属性
        • クラスパス配下のマッピング定義ファイルの位置を指定する

あとはオブジェクトとテーブルの関連を記述するファイル。
「***.hbm.xml
置き場所は「hibernate.cfg.xml」で指定。
Mavenプロジェクト構造のjava/main/resources直下に置いた。
■Book.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="jp.sample.vo">
  <class name="Book" table="BOOK">
    <id name="isbn" column="isbn">
      <generator class="increment"/>
    </id>
    <property name="date" type="timestamp" column="date"/>
    <property name="title"/>
  </class>
</hibernate-mapping>
  • class要素
      • name属性
        • クラス名(FQN)
      • table属性
        • オブジェクトに対応するテーブル名
  • id要素
    • テーブル中でユニークなカラム(プライマリーキー)を設定する要素
      • name属性
        • オブジェクトクラスのユニークなカラムに対応するフィールド名
      • column属性
  • property要素
    • テーブル中でないユニークなカラム(プライマリーキー)を設定する要素
      • name属性
        • テーブルのカラムに対応するオブジェクトのフィールド名
      • type属性
        • オブジェクトのフィールドの型、設定しない場合はHibernateが頑張ってくれる
      • column属性
        • テーブルのカラム名、オブジェクトのフィールド名と一致する場合は設定不要

■Book.java

package jp.sample.vo;

import java.util.Date;

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;
	}

	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;
	}

	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 jp.sample.vo.Book;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Main {

	public static void main(String[] args) {
		// hibernate.cfg.xmlから設定を読み込む
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

		// DB登録
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		session.save(new Book("Hibernate", new Date()));
		session.save(new Book("Java", new Date()));
		session.getTransaction().commit();
		session.close();

		// DB参照
		session = sessionFactory.openSession();
		session.beginTransaction();
		List<Book> result = (List<Book>) session.createQuery("from jp.sample.vo.Book").list();
		for (Book event : result) {
			System.out.println("Book (" + event.getDate() + ") : "
					+ event.getTitle());
		}
		session.getTransaction().commit();
		session.close();

		if (sessionFactory != null) {
			sessionFactory.close();
		}
	}
}
はまりポイント
  • List result = (List) session.createQuery("from jp.sample.vo.Book").list();
    • フルパスにしないといけないところではまった。。。
    • 「from jp.sample.vo.Book」でなく、「from Book」だとDB参照の際にエラーになった

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

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


参考
http://www.hibernate.org/