Hibernate

Hibernate とは

JavaオブジェクトとRDBのマッピングを行うオブジェクト関係マッピングツール(ORM)

ダウンロード/インストール

http://hibernate.org/ の Hibernate ORM からダウンロード、解凍し、jar にClassPath を通す。
※Webアプリの場合は、WEB-INF/lib に配置する。(とりあえず lib/required 配下のものを全て配置する)

設定ファイルの記述

hibernate.cfg.xml を以下の通り編集し、CLASSPATHの通っているフォルダに保存する。

<!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">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://127.0.0.1:3306/dbname?useUnicode=true&characterEncoding=UTF-8</property>
		<property name="connection.username">username</property>
		<property name="connection.password">password</property>
		<property name="connection.pool_size">1</property>
		<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
		<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">none</property>
	</session-factory>
</hibernate-configuration>

テーブル/データの作成

CREATE TABLE `books` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `isbn` varchar(255) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `price` int(11) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into books(isbn,title,price,created_at,updated_at)
 values('978-4822280536', 'デッドライン', 2376, NOW(), NOW())
          ,('978-4873114798', 'プログラマが知るべき97のこと', 2052, NOW(), NOW())
          ,('978-4873115658', 'リーダブルコード', 2592, NOW(), NOW());

CREATE TABLE `emps` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(255) DEFAULT NULL,
  `dept_id` int(11) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into emps(emp_name, dept_id, created_at, updated_at)
 values('従業員1', 1, NOW(), NOW())
      ,('従業員2', 1, NOW(), NOW())
      ,('従業員3', 2, NOW(), NOW())
      ,('従業員4', 3, NOW(), NOW());


CREATE TABLE `depts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dept_name` varchar(255) DEFAULT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into depts(dept_name, created_at, updated_at)
 values('部門A', NOW(), NOW())
      ,('部門B', NOW(), NOW())
      ,('部門C', NOW(), NOW());

リソースクラスの作成

package example.entity;

import java.io.Serializable;

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

@Entity
public class Books implements Serializable {

	private static final long serialVersionUID = 1L;

	private int id;

	private String isbn;

	private String title;

	private int price;

	@Temporal(TemporalType.TIMESTAMP)
	private java.util.Date created_at;

	@Temporal(TemporalType.TIMESTAMP)
	private java.util.Date updated_at;

	public Books(){
		created_at = new java.util.Date();
		updated_at = new java.util.Date();
	}
	
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getIsbn() {
		return isbn;
	}
	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	public java.util.Date getCreated_at() {
		return created_at;
	}
	public void setCreated_at(java.util.Date created_at) {
		this.created_at = created_at;
	}
	public java.util.Date getUpdated_at() {
		return updated_at;
	}
	public void setUpdated_at(java.util.Date updated_at) {
		this.updated_at = updated_at;
	}
} 

※DB定義とJavaオブジェクトで列名が異なる場合は、@Column を使用してマッピングを行う事ができる。
※マッピング定義はXMLで定義する事もできる。

検索/登録処理の作成

基底クラス

package example;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class SampleBase {

	public static SessionFactory getSessionFactory(){
		Configuration configuration = new Configuration();
	    configuration.configure();
	    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();       
	    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	    return sessionFactory;
	} 
}

ORMを使用してデータ登録

public class SampleCreate01 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();

		session.beginTransaction();

		Books newBook = new Books();
		newBook.setIsbn("TEST001");
		newBook.setTitle("テストタイトル1");
		newBook.setPrice(1080);
		session.save(newBook);

		session.getTransaction().commit();
		session.close();
	} 
}

SQLでデータ登録

public class SampleCreate02 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();

		session.beginTransaction();

		String sql = "insert into books(isbn,title,price,created_at,updated_at)"
		           + " values(:isbn,:title,:price,now(),now())";

		int cnt = session.createSQLQuery(sql)
		                 .setParameter("isbn" , "TEST1")
		                 .setParameter("title", "テストタイトル1")
		                 .setParameter("price", 1080)
		                 .executeUpdate();

		System.out.println(cnt + "件登録しました");
		
		
		session.getTransaction().commit();
		session.close();
	} 
}

HQLでデータ取得し、リソースオブジェクトにマッピング.

public class SampleSelectHql01 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();
		List<Books> results = session.createQuery( "from Books" ).list();
		System.out.println("size : " + results.size());
		if (results != null && results.size() > 0) {
			for (Books book : results) {
				System.out.println("-----------------------------------------");
				System.out.println("id      : " + book.getId());
				System.out.println("isbn    : " + book.getIsbn());
				System.out.println("title   : " + book.getTitle());
				System.out.println("price   : " + book.getPrice());
				System.out.println("created : " + book.getCreated_at());
				System.out.println("updated : " + book.getUpdated_at());
			}
		}
		session.close();
	} 
} 

HQLで条件を指定してデータ取得し、リソースオブジェクトにマッピング.

public class SampleSelectHql02 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();
		String hql = "from Books where id = :book_id";
		List<Books> results = session.createQuery(hql)
		                             .setParameter("book_id", 1)
		                             .list();
		for (Books book : results) {
			System.out.println("-----------------------------------------");
			System.out.println("id      : " + book.getId());
			System.out.println("isbn    : " + book.getIsbn());
			System.out.println("title   : " + book.getTitle());
			System.out.println("price   : " + book.getPrice());
			System.out.println("created : " + book.getCreated_at());
			System.out.println("updated : " + book.getUpdated_at());
		}
		session.close();
	} 
} 

HQLでテーブル結合してデータ取得し、リソースオブジェクトにマッピング

public class SampleSelectHql03 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();
		String hql = "from Emps e,Depts d where e.deptId = d.id and d.id = :dept_id";
		List<Object[]> results = session.createQuery(hql)
		                                .setParameter("dept_id", 1)
		                                .list();
		for (Object[] row : results) {
			Emps  emp  = (Emps) row[0];
			Depts dept = (Depts)row[1];
			System.out.println("-----------------------------------------");
			System.out.println("emp_id    : " + emp.getEmpId());
			System.out.println("name      : " + emp.getEmpName());
			System.out.println("dept_id   : " + dept.getId());
			System.out.println("dept_name : " + dept.getDeptName());
			System.out.println("created   : " + emp.getCreatedAt());
			System.out.println("updated   : " + emp.getUpdatedAt());
		}
		session.close();
	} 
} 

SQLでデータ取得し、リソースオブジェクトにマッピング

public class SampleSelectSql01 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();
		String sql = "select id,isbn,title,price,created_at,updated_at from books";
		List<Books> results = session.createSQLQuery(sql).addEntity(Books.class).list();
		for (Books row : results) {
			System.out.println("-----------------------------------------");
			System.out.println("id      : " + row.getId());
			System.out.println("isbn    : " + row.getIsbn());
			System.out.println("title   : " + row.getTitle());
			System.out.println("price   : " + row.getPrice());
			System.out.println("created : " + row.getCreated_at());
			System.out.println("updated : " + row.getUpdated_at());
		}
		session.close();
	} 
} 

SQLで条件を指定してデータ取得し、リソースオブジェクトにマッピング

public class SampleSelectSql02 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();
		String sql = "select b.* from books b where b.id = :book_id";
		List<Books> results = session.createSQLQuery(sql)
				.addEntity(Books.class)
				.setParameter("book_id", 1)
				.list();
		for (Books book : results) {
			System.out.println("-----------------------------------------");
			System.out.println("id      : " + book.getId());
			System.out.println("isbn    : " + book.getIsbn());
			System.out.println("title   : " + book.getTitle());
			System.out.println("price   : " + book.getPrice());
			System.out.println("created : " + book.getCreated_at());
			System.out.println("updated : " + book.getUpdated_at());
		}

		session.close();
	} 
} 

SQLでテーブル結合してデータ取得し、リソースオブジェクトにマッピング

public class SampleSelectSql03 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();
		String sql = "select {e.*}, {d.*}"
		           + " from emps e inner join depts d on e.dept_id = d.id"
		           + " where d.id = :dept_id"
		           + " order by e.id";
		List<Object[]> results = session.createSQLQuery(sql)
		                                .addEntity("e", Emps.class)
		                                .addEntity("d", Depts.class)
		                                .setParameter("dept_id", 1)
		                                .list();
		for (Object[] row : results) {
			Emps  emp  = (Emps)row[0];
			Depts dept = (Depts)row[1];
			System.out.println("-----------------------------------------");
			System.out.println("emp_id    : " + emp.getEmpId());
			System.out.println("name      : " + emp.getEmpName());
			System.out.println("dept_id   : " + dept.getId());
			System.out.println("dept_name : " + dept.getDeptName());
			System.out.println("created   : " + emp.getCreatedAt());
			System.out.println("updated   : " + emp.getUpdatedAt());
		}
		session.close();
	} 
} 

SQLでデータ取得(オブジェクトマッピングなし)

public class SampleSelectSql09 extends SampleBase {

	public static void main(String[] args) {
    	SessionFactory sessionFactory = getSessionFactory();
    	Session session = sessionFactory.openSession();
		List<Object[]> results = session.createSQLQuery("select id,isbn,title,price,created_at,updated_at from books").list();
		for (Object[] row : results) {
			int              id           = (Integer)     row[0];
			String         isbn       = (String)       row[1];
			String         title        = (String)       row[2];
			int              price      = (Integer)     row[3];
			Timestamp created  = (Timestamp)row[4];
			Timestamp updated = (Timestamp)row[5];
			System.out.println("-----------------------------------------");
			System.out.println("id      : " + id);
			System.out.println("isbn    : " + isbn);
			System.out.println("title   : " + title);
			System.out.println("price   : " + price);
			System.out.println("created : " + created);
			System.out.println("updated : " + updated);
		}
		session.close();
	} 
} 

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2012-08-05 (日) 18:46:12 (4504d)