Hibernateを使ってみる(Annotationを使って)
プロジェクト作成に下記を実行。
mvn archetype:generate -DgroupId=study -DartifactId=HibernateAnnotationSample -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>HibernateAnnotationSample</artifactId> <packaging>jar</packaging> <version>1.0.0</version> <name>HibernateAnnotationSample</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> <!-- Names the annotated entity class --> <mapping class="jp.sample.vo.Book" /> </session-factory> </hibernate-configuration>
- mapping要素
-
- class属性
- 永続化対象オブジェクトをフルパスで指定する。
- class属性
-
永続化対象オブジェクトについては下記リンクの「■hibernate.cfg.xml」の設定とまったく同じにしてある。
設定ファイルで書く場合とアノテーションで書く場合を比べると面白い。
http://d.hatena.ne.jp/tanakakns/20120615/1339735447
■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 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(); } } }
PostgreSQL9.1に下記でテーブル作成。
create table BOOK ( isbn integer primary key, title varchar, date timestamp );