jpa チュートリアル
jpaを使い始める
サーチ…
備考
JPAは、Java Persistence APIです.Java Persistence APIは、Javaオブジェクトとそれらの関係をリレーショナル・データベースにマッピングする処理を指定します。これは、オブジェクト・リレーショナル・マッパー(ORM)と呼ばれます。これは、より低レベルのJDBCの代替(または補足)です。これは、Java指向のアプローチを追求し、複雑なオブジェクトグラフを永続化する必要がある場合に最も便利です。
JPA自体は実装ではありません。これには永続プロバイダが必要です(例を参照)。最新のJPA 2.1標準の実装は、 EclipseLink (「仕様の実装が可能であることを証明する」という意味のJPA 2.1のリファレンス実装です)です。 Hibernate 、およびDataNucleusが含まれます。
メタデータ
Javaオブジェクトとデータベーステーブル間のマッピングは、 永続性メタデータによって定義されます。 JPAプロバイダは、永続性メタデータ情報を使用して正しいデータベース操作を実行します。 JPAは通常、Javaクラスの注釈を使用してメタデータを定義します。
オブジェクト・リレーショナル・エンティティ・アーキテクチャ
エンティティアーキテクチャは次のもので構成されます。
- 実体
- 持続性単位
- 永続コンテキスト
- エンティティマネージャファクトリ
- エンティティマネージャ
バージョン
インストールまたはセットアップ
クラスパス要件
Eclipselink
Eclipselink APIとJPA APIを含める必要があります。 Mavenの依存関係の例:
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.1</version>
</dependency>
<!-- ... -->
</dependencies>
休止状態
Hibernate-coreが必要です。 Mavenの依存関係の例:
<dependencies>
<dependency>
<!-- requires Java8! -->
<!-- as of 5.2, hibernate-entitymanager is merged into hibernate-core -->
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0</version>
</dependency>
<!-- ... -->
</dependencies>
DataNucleus
datanucleus-core、datanucleus-api-jpaおよびdatanucleus-rdbms(RDBMSデータストアを使用する場合)が必要です。 Mavenの依存関係の例:
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-core</artifactId>
<version>5.0.0-release</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-api-jpa</artifactId>
<version>5.0.0-release</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-rdbms</artifactId>
<version>5.0.0-release</version>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.2</version>
</dependency>
<!-- ... -->
</dependencies>
設定の詳細
JPAでは、CLASSPATHのルートにあるMETA-INF
下にあるファイルpersistence.xmlを使用する必要があります。このファイルには、JPAが動作可能な永続性ユニットの定義が含まれています。
JPAはさらに、 META-INF
下に置かれたマッピング構成ファイルorm.xmlを使用できます。このマッピングファイルは、クラスがデータストアにどのようにマップされるかを設定するために使用され、JPAエンティティクラス自体でJavaアノテーションを使用する代替/補足です。
最小限のpersistence.xmlの例
Hibernate(および埋め込まれたH2 DB)
<?xml version="1.0" encoding="UTF-8"?>
<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_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>my.application.entities.MyEntity</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:data/myDB.db" />
<property name="javax.persistence.jdbc.user" value="sa" />
<!-- DDL change options -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
</properties>
</persistence-unit>
</persistence>
Eclipselink(および埋め込まれたH2 DB)
<?xml version="1.0" encoding="UTF-8"?>
<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_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnit">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>my.application.entities.MyEntity</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:data/myDB.db"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<!-- Schema generation : drop and create tables -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create-tables" />
</properties>
</persistence-unit>
</persistence>
DataNucleus(および埋め込みH2 DB)
<?xml version="1.0" encoding="UTF-8"?>
<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_1.xsd"
version="2.1">
<persistence-unit name="persistenceUnit">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<class>my.application.entities.MyEntity</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:data/myDB.db"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<!-- Schema generation : drop and create tables -->
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create-tables" />
</properties>
</persistence-unit>
</persistence>
こんにちは世界
単純なハローワールドを作成するための基本的なコンポーネントをすべて見てみましょう。
- 使用するJPA 2.1の実装を定義する
-
persistence-unit
作成するデータベースへの接続を構築する - エンティティを実装します。
- DAO(データアクセスオブジェクト)を実装してエンティティを操作する
- アプリケーションのテスト
図書館
Mavenを使うには、この依存関係が必要です。
<dependencies>
<!-- JPA is a spec, I'll use the implementation with HIBERNATE -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.6.Final</version>
</dependency>
<!-- JDBC Driver, use in memory DB -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
</dependencies>
パーシスタンスユニット
resourcesフォルダで、 persistence.xml
というファイルを作成する必要があります。それを定義する最も簡単な方法は次のようなものです:
<persistence-unit name="hello-jpa-pu" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<!-- ~ = relative to current user home directory -->
<property name="javax.persistence.jdbc.url" value="jdbc:h2:./test.db"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.show_sql" value="true"/>
<!-- This create automatically the DDL of the database's table -->
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
エンティティを実装する
私はクラスBiker
を作成する:
package it.hello.jpa.entities;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
@Entity
@Table(name = "BIKER")
public class Biker implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "bikerName")
private String name;
@Column(unique = true, updatable = false)
private String battleName;
private Boolean beard;
@Temporal(TemporalType.DATE)
private Date birthday;
@Temporal(TemporalType.TIME)
private Date registrationDate;
@Transient // --> this annotiation make the field transient only for JPA
private String criminalRecord;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getBattleName() {
return battleName;
}
public void setBattleName(String battleName) {
this.battleName = battleName;
}
public Boolean getBeard() {
return this.beard;
}
public void setBeard(Boolean beard) {
this.beard = beard;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getCriminalRecord() {
return criminalRecord;
}
public void setCriminalRecord(String criminalRecord) {
this.criminalRecord = criminalRecord;
}
}
DAOを実装する
package it.hello.jpa.business;
import it.hello.jpa.entities.Biker;
import javax.persistence.EntityManager;
import java.util.List;
public class MotorcycleRally {
public Biker saveBiker(Biker biker) {
EntityManager em = EntityManagerUtil.getEntityManager();
em.getTransaction().begin();
em.persist(biker);
em.getTransaction().commit();
return biker;
}
}
EntityManagerUtil
はシングルトンです:
package it.hello.jpa.utils;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerUtil {
// USE THE SAME NAME IN persistence.xml!
public static final String PERSISTENCE_UNIT_NAME = "hello-jpa-pu";
private static EntityManager entityManager;
private EntityManagerUtil() {
}
public static EntityManager getEntityManager() {
if (entityManager == null) {
// the same in persistence.xml
EntityManagerFactory emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
return emFactory.createEntityManager();
}
return entityManager;
}
}
アプリケーションのテスト
パッケージit.hello.jpa.test;
パブリッククラスTestJpa {
@Test
public void insertBiker() {
MotorcycleRally crud = new MotorcycleRally();
Biker biker = new Biker();
biker.setName("Manuel");
biker.setBeard(false);
biker = crud.saveBiker(biker);
Assert.assertEquals(biker.getId(), Long.valueOf(1L));
}
}
出力は次のようになります。
実行中it.hello.jpa.test.TestJpa Hibernate:ドロップテーブルBIKERもしあればHibernate:もしhibernate_sequenceが存在すればhibernate:シーケンスを作成するhibernate_sequenceは1ずつ増分で始まるHibernate:create table BIKER(id bigint not null、battleName varchar(255) (BattleName、beard、birthday、bikerName、registrationDate)Bibernate:BIKER(BattleName、beard、beard、bikerName)を追加します。 2019、2017 11:00:02 PM orgHibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation INFO:HHH000204:PersistenceUnitInfoを処理する(名前:hello- jpa-pu ...]結果:
テスト実行:1、失敗:0、エラー:0、スキップ:0