the detail of jpa 20
DESCRIPTION
This presentation explains the feature of the JPA 2.0.TRANSCRIPT
![Page 1: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/1.jpg)
1 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Java Persistence API の詳細ついて 日本オラクル Fusion Middleware 製品事業統括本部 シニア Java エバンジェリスト 寺田 佳央 (http://yoshio3.com)
![Page 2: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/2.jpg)
2 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
以下の事項は、弊社の一般的な製品の方向性に関する概要を説明するものです。また、情報提供を唯一の目的とするものであり、いかなる契約にも組み込むことはできません。以下の事項は、マテリアルやコード、機能を提供することをコミットメント(確約)するものではないため、購買決定を行う際の判断材料になさらないで下さい。オラクル製品に関して記載されている機能の開発、リリースおよび時期については、弊社の裁量により決定されます。
Oracleは、米国オラクルコーポレーション及びその子会社、関連会社の米国及びその他の国における登録商標です。文中の社名、商品名等は各社の商標または登録商標である場合があります。
![Page 3: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/3.jpg)
3 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
はじめに
![Page 4: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/4.jpg)
4 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Java からの DB アクセス • アプリケーションにとって非常に重要な部分
– パフォーマンスを劣化させないように – DBデータの整合性を失わない – 開発効率/メンテナンス性をどうやって高めるか
• どんな技術をお使いですか? – JDBC – EJB2.0 CMP Entity Bean – JDO(Java Data Objects) – O/Rマッピングツール …
![Page 5: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/5.jpg)
5 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JDBC 抽象化レイヤ • 実際にはアプリケーションコードとDBアクセスコードを 分離するための抽象化レイヤを設けるのが一般的 – アプリケーション側ではSQL/JDBCのコードを書かない – Value Object (JavaBeans)でデータのやり取り
• 自作フレームワーク – SQLのパターンが少数の場合
• O/Rマッピングツール – GUIによるマッピング定義 – SQL自動生成 – プラットフォーム移植性(DB、AS)
![Page 6: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/6.jpg)
6 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Java からの DB アクセス • O/R(Object-Relational)マッピングツール
– 煩雑なJDBCコーディングなしでDBアクセスを 可能にするためのツール
– Javaクラスとテーブルの対応付け • オブジェクト指向 vs 正規化 (インピーダンス・ミスマッチ) • ORMツールにより設計思想のギャップを埋める
– プログラムミスによるリスクを回避 • 代表的なORMツール
– Apache iBATIS – Hibernate – Oracle TopLink
![Page 7: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/7.jpg)
7 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
public Customer findCustomer(Integer id) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; Customer customer = null; ArrayList orders = null; try { conn = ds.getConnection(); pstmt = conn.prepareStatement( "SELECT C.ID, C.NAME, C.EMAIL, C.PHONE, " + "O.ID, O.PRODUCT, O.PRICE FROM CUSTOMER C, ORD O " + "WHERE C.ID = O.CID AND C.ID = ?"); pstmt.setInt(1, id.intValue()); rs = pstmt.executeQuery(); orders = new ArrayList(); int order_count = 0; while (rs.next()) { if (order_count == 0) { customer = new Customer(); customer.setId(new Integer(rs.getInt(1))); customer.setName(rs.getString(2)); customer.setEmail(rs.getString(3)); customer.setPhone(rs.getString(4)); } Order order = new Order(); order.setId(new Integer(rs.getInt(5))); order.setProduct(rs.getString(6)); order.setPrice(new Integer(rs.getInt(7))); order.setOwner(customer); orders.add(order); order_count++; } customer.setOrders(orders); } catch (SQLException ex) { ex.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (conn != null) conn.close(); } catch (SQLException ex) {} } return customer; }
@PersistenceContext( unitName="default" ) EntityManager em; public Customer findCustomer(Integer id) { return em.find( Customer.class, id ); }
![Page 8: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/8.jpg)
8 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
• JDBC 直接の場合、考慮実装しなければならない事が多い パフォーマンスを劣化させる要因 ・クライアントごとに発生するDBアクセスの時間 ・接続プールからのJDBC接続の取得待ち ・Javaオブジェクトの生成コスト ・JavaオブジェクトのGCに要するコスト
キャッシュを使用することで ・DBアクセス回数の低減 ・JDBC接続の使用時間の短縮 ・生成したJavaオブジェクトの使い回し
問合せ
クライアント
DB
SQL
問合せ
クライアント DB
キャッシュ
SQL
キャッシュ設定はクラス単位から ・静的データ 効果大
商品、顧客 ・動的データ 効果小
発注情報、配送情報
![Page 9: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/9.jpg)
9 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Java Persistence API
![Page 10: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/10.jpg)
10 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPA の主要コンポーネント
![Page 11: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/11.jpg)
11 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPA の主要コンポーネント
![Page 12: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/12.jpg)
12 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPA の構成要素
Persistence Context
Entity
EntityManager Factory
EntityManager API persist() remove() find() …
Persistence Unit Persistence.xml
![Page 13: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/13.jpg)
13 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
PersistenceUnitと設定ファイル
Persistence Context
Entity
EntityManager Factory
EntityManager API persist() remove() find() …
Persistence Unit Persistence.xml
![Page 14: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/14.jpg)
14 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Persistence Unit • Persistence Unit
– EntityManagerのインスタンスを生成するファクトリを定義 – EntityクラスをRDBにマッピングする設定 – データベースへの接続用データソース設定 – など
• persistence.xml 設定ファイル – 1つ以上の Persistence Unitを定義可能 – @Entity アノテーションが付加されたクラスを検索
![Page 15: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/15.jpg)
15 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
<persistence version="2.0" 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">! <persistence-unit name=”SamplePU" transaction-type="JTA">! <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>! <jta-data-source>jdbc/sample</jta-data-source>! <properties>! <property name="eclipselink.ddl-generation" value="create-tables"/>! </properties>! </persistence-unit>!</persistence>!
Persistence.xml
![Page 16: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/16.jpg)
16 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity Persistence Unit Persistence.xml
EntityManager Factory
Persistence Context
EntityManager API persist() remove() find() …
Entity
Persistence ContextとEntityManager
![Page 17: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/17.jpg)
17 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
EntityManager
• EntityManager – Entityのインスタンスのライフサイクルを管理するAPIを提供 – 永続化エンジンとプログラミングによる対話が可能 – 提供機能の例
• ライフサイクル系操作:persist(), remove(), refresh(), merge() • 検索系処理:find(), getReference() • クエリの発行系:createQuery() createNamedQuery(), createNativeQuery()
• Persistence Contextの管理系:flush(), clear(), close(), getTransaction()
![Page 18: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/18.jpg)
18 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Persistence Context
• Persistence Context – 管理する Entity の集合 – 1つの Persistence Unit に属する
![Page 19: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/19.jpg)
19 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Servlet EJB Javaアプリ
persist() remove() refresh() merge() find() createQuery() contains() detach() lock()
EntityManager
Persistence Context
EntityManagerで 管理されるEntity
Persistence ContextとEntityManager
![Page 20: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/20.jpg)
20 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Persistence ContextとEntityManager
• 2種類のEntityManager – コンテナ管理のEntityManager : Java EE コンテナで使用 – アプリケーション管理のEntityManager:Java SE/EE で使用
• 2種類のPersistence Context – トランザクションスコープのPersistence Context – Extended Persistence Context
![Page 21: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/21.jpg)
21 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
コンテナ管理のEntityManager
• Java EE コンテナによって管理 • DI/JNDI によりEntityManagerインスタンスを取得
– @PersistenceContext EntityManager entityManager;
![Page 22: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/22.jpg)
22 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
@Stateless! public class MyEnterpriseBean {! @PersistenceContext(unitName = ”MYJPA_PU")! private EntityManager em;!! public void createMyEntity(Customer customer) {! em.persist(customer);! }! }!
コンテナがトランザクションを管理 コミット、ロールバック等は自動的に実施
コンテナ管理のEntityManager
![Page 23: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/23.jpg)
23 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
アプリケーション管理のEntityManager
• EntityManagerFactoryから生成 – EntityManager em = emf.createEntityManager();
• アプリケーションでライフサイクルを管理 • Java SE 環境で利用可能 • Extended Persistence Contextの使用が必須 • JTA(Web)もしくはRESOURCE_LOCAL(Java SE)のトランザクションタイプを使用
![Page 24: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/24.jpg)
24 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
アプリケーション管理のEntityManager
EntityManagerFactory emf = ! Persistence.createEntityManagerFactory(”MYJPA_PU");! EntityManager em = emf.createEntityManager();! EntityTransaction tx = em.getTransaction();!! tx.begin();! em.persist(customer);! tx.commit();!! em.close();! emf.close();!
アプリケーションでトランザクションを管理 コミット、ロールバック等の実装が必要
![Page 25: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/25.jpg)
25 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Persistence を実現するための概念
PersistenceUnit
EntityManager Factory
EntityManager PersistenceContext
設定
生成 管理
![Page 26: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/26.jpg)
26 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity
Persistence Context EntityManager
Factory
EntityManager API persist() remove() find() …
Persistence Unit Persistence.xml
Entity
![Page 27: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/27.jpg)
27 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity とテーブルのかんたんなマッピング
@Entity! public class Customer implements Serializable {! @Id! private Long id;! private String address1;! private long age;! private String name;! private String telephone;! //セッタ・ゲッタ }!!
DBのテーブル
Entity クラス
管理下にない場合は単なるPOJO
![Page 28: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/28.jpg)
28 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
@Entity! @Table(name=“ORACLE_CUSTOMER”)! public class Customer implements Serializable {! @Id! private Long id;! private String address1;! private long age;! private String name;! private String telephone;! //セッタ・ゲッタ }!!
ORACLE_CUSTOMERテーブル にマッピング
必要時のみデフォルト設定を上書きする手法 (Configuration By Exception)
![Page 29: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/29.jpg)
29 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
@Entity! public class Customer implements Serializable {! @Id! private Long id;! @NotNull //入力必須! @Size(min = 1, max = 512) //入力サイズの変更! @Column(name = ”FULL_ADDRESS“) //デフォルトのカラム名をFULL_ADDRESSに変更! private String address1;! private long age;! private String name;! private String telephone;! //セッタ・ゲッタ }!!
デフォルトのカラム設定を上書き
![Page 30: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/30.jpg)
30 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
@Entity! public class Customer implements Serializable {! @Id! private Long id;! private String address1;! private long age;! private String name;! private String telephone;! @Basic(fetch = FetchType.LAZY)//写真の取得要求があるまで遅らせる! @Lob! private byte[] picture;! }!
LAZY LOAD(遅延読み込み)
![Page 31: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/31.jpg)
31 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
@Entity! public class Customer implements Serializable {! @Id! private Long id;! private String address1;! private long age;! private String name;! private String telephone;! @Temporal(TemporalType.DATE) //DATE型を使用! private Date dateOfBirth;! @Temporal(TemporalType.TIMESTAMP) //TIMESTAMP型を使用! private Date creationDate;!}!
@Temporal(日付、時刻)
![Page 32: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/32.jpg)
32 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
@Embeddable! public class Address{! private String street;! private String town;! private String city;! private String prefecture;! }!!
組み込み可能コレクション
@Entity! public class Person {! …! @ElementCollection! private Set<Address> addresses;! }!!
![Page 33: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/33.jpg)
33 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity のライフサイクル Entityの生成(new MyEntity())
em.persist()
Persistence Context
管理状態の Entity
管理状態の Entity
管理状態の Entity
デタッチ状態の Entity
em.merge()
tx.flush() tx.commit()
削除されたEntity
em.remove()
tx.commit() tx.rolleback()
tx.reflesh()
![Page 34: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/34.jpg)
34 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity のライフサイクル EntityManagerFactory emf = ! Persistence.createEntityManagerFactory(”MYJPA_PU");! EntityManager em = emf.createEntityManager();! EntityTransaction tx = em.getTransaction();! Customer customer = new Customer(); //Entityの生成! tx.begin();! em.persist(customer); //管理状態のEntity! tx.commit(); //デタッチ状態になるEntity! //JavaのHeapにはcustomerは存在するが、JPAの管理状態から外れデタッチ状態! //この状態でcustomerにたいする操作を行った場合は、merge()で同期! em.close();! emf.close();!
![Page 35: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/35.jpg)
35 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
クエリの実行方法
![Page 36: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/36.jpg)
36 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity と ID を使用した検索
Customer customer = em.find(Customer.class, 1234L)!if (customer!= null) {! //オブジェクトを処理する }
try {! Customer customer = ! em.getReference(Customer.class, 1234L)! //オブジェクトを処理する } catch(EntityNotFoundException ex) {! //エンティティが見つからない }!
![Page 37: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/37.jpg)
37 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Customer customer = ! new Customer(”Taro", ”Yamada", ”[email protected]");!tx.begin();!em.persist(customer);!tx.commit();!tx.begin();!em.remove(customer);!tx.commit();!
Entity の生成と削除
![Page 38: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/38.jpg)
38 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPQL(Java Persistence Query Language)
• SQLに類似したクエリ言語 • Entity を使用したクエリ表現 • select, update, delete などの機能を提供 • データベースに非依存
SELECT c FROM Customer c!
FROM 句で別名を作成 結果は Customer インスタンス
![Page 39: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/39.jpg)
39 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPQLクエリ (SELECT 句の例)
SELECT c FROM Customer c WHERE c.lastName = ’Yamada'!
Customer 苗字が ’Yamada’ に一致する0件以上のインスタンスの取得
SELECT c.firstName FROM Customer c!
Customer 名の文字列、もしくは文字列のコレクションを取得
SELECT c.firstName, c.lastName FROM Customer c!
Customer 氏名共に取得
![Page 40: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/40.jpg)
40 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
SELECT c FROM Customer c!WHERE c.firstName = ’Taro' AND c.address = ’Tokyo'!
JPQLクエリ (WHERE 句の例)
AND, OR でクエリをさらに限定 SELECT c FROM Customer c WHERE c.age > 18!
WHERE句で =, >, >=, <, <=, <>, (NOT) BETWEEN, (NOT) LIKE, (NOT) IN, IS (NOT) NULL, IS (NOT) EMPTY, (NOT) MEMBER (OF) などの比較演算子を 利用可能
SELECT c FROM Customer c!WHERE c.age NOT BETWEEN 40 AND 50!
![Page 41: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/41.jpg)
41 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPQLクエリ (パラメータの動的バインド例)
SELECT c FROM Customer c!WHERE c.firstName = ?1 AND c.address = ?2!
? (疑問符)の後に整数を指定 → 実行時引数の番号
SELECT c FROM Customer c!WHERE c.firstName = :fname AND c.address = :address!
: (セミコロン)の後に名前を指定 → 実行時引数の名前
![Page 42: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/42.jpg)
42 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPQLクエリ (パラメータの動的バインド例)
TypedQuery<Customer> query = ! em.createQuery(! "SELECT c FROM Customer c WHERE c.name = ?1”,Customer.class);! query.setParameter(1, name);!
TypedQuery<Customer> query = ! em.createQuery(! "SELECT c FROM Customer c WHERE c.name = :name”,Customer.class);! query.setParameter(“name”, name);!
Query#setParameter(position,value)でクエリの引数に代入
![Page 43: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/43.jpg)
43 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPQL(サブクエリ、オーダ)
SELECT c FROM Customer c!WHERE c.age = (SELECT MIN(cust. age) FROM Customer cust)!
WHERE句またはHAVING句の条件式に埋め込むSELECT
SELECT c FROM Customer c WHERE c.age > 18 ORDER BY c.age DESC!
クエリによって得られる結果のソート (ASC: 昇順、DESC: 降順)
![Page 44: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/44.jpg)
44 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
• 検索結果を変更したい場合、テーブル定義の変更ができない場合に有効
• CASE – CASE{WHEN <cond_exp> THEN <scalar_expr>} + ELSE <scalar_exp> END
• COALESCE – COALESCE(<scalar_exp> {,<scalar_expr>} + )
• NULLIF – NULLIF(<scalar_expr1>, <scalar_expr2>)
ANSI SQL-92 CASE Expression 対応
![Page 45: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/45.jpg)
45 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
UPDATE Employee e!SET e.salary =! CASE e.rating ! WHEN 1 THEN e.salary * 1.2! WHEN 2 THEN e.salary * 1.1! ELSE e.salary * 1.02! END!
CASE 式のサンプル
• 社員の評価レートが1の場合基本給の1.2倍
• 社員の評価レートが2の場合基本給の1.1倍
• それ以外は、1.02倍
勤務評価に応じた給料の昇給
![Page 46: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/46.jpg)
46 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
データの一括操作
DELETE FROM Customer c WHERE c.age < 18!
一括削除 (EntityManager#remove()より効率的)
UPDATE Customer c SET c.firstName = 'TOO YOUNG’ WHERE c.age < 18!
一括更新 (EntityManager#remove()より効率的)
![Page 47: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/47.jpg)
47 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
プログラミングによるクエリ(Criteria API)
• クエリーの制御をJavaオブジェクトで制御 – JPA1.0ではJPQL/Native SQLでクエリーを記載 – JPQLで可能なことはプログラム上で実現可能
• Criteria APIはクエリー実行結果の型の安全性が向上 – クエリー実行におけるランタイムエラーの発生率が減少 – 統合開発環境の型チェックを利用し安全に実装可能
• JPQLはSQLに精通した開発者に有効 – 統合開発環境が自動的に雛形を生成(開発効率の向上) – 開発者に選択肢を提供
• オブジェクトベース、文字列ベースのクエリーを提供
![Page 48: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/48.jpg)
48 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Criteria API
• CriteriaBuilder : – CriteriaQueryオブジェクトを生成するファクトリ – EntityManager#getCriteriaBuilder()より取得
• CriteriaQuery : – クエリーの実行結果の型を返す – <T> CriteriaQuery<T> createQuery(Class<T> resultClass)
• Root : – クエリーの範囲指定
• その他 – Join, ListJoin, MapJoin, Path, Subqueryなど
![Page 49: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/49.jpg)
49 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Criteria API実装と対応するJPQL
EntityManager em = … ;!CriteriaBuilder cb = em.getCriteriaBuilder();!CriteriaQuery<Person> p = cb.createQuery(Person.class);!Root<Person> person = p.from(Person.class);!p.select(person).where(! cb.equal(person.get(“name”),”Taro Yamada”));!
対応する JPQL 文 SELECT p FROM Person p WHERE p.name = 'Taro Yamada’
![Page 50: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/50.jpg)
50 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Metamodel API
• 強力な型チェックを可能 – ランタイムエラーの排除
• 文字列によるエンティティの属性へのアクセスを排除 – コンパイル時に属性の有無、型チェックを実施
• Metamodelクラスの生成 – _を付加した正規化したMetamodelクラスを生成 – IDEで自動生成(※NetBeans は Ver 7.0 より)
• プログラム上で動的に生成
![Page 51: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/51.jpg)
51 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Metamodel APIを使用しない場合の潜在的問題点
EntityManager em = … ;! CriteriaBuilder cb = em.getCriteriaBuilder();! CriteriaQuery<Person> p = cb.createQuery(Person.class);! Root<Person> person = p.from(Person.class);! p.select(person).where(! cb.equal(person.get(“nema”),”Taro Yamada”));!
“name” と入力すべき所を “nema” とタイプミス ランタイムエラーが発生
![Page 52: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/52.jpg)
52 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
@Entity!!public class Person {! @Id! @GeneratedValue(strategy = ! GenerationType.AUTO)! private Long id;! private String name;! Private Integer age;!}!
import javax.persistence.metamodel.SingularAttribute;[email protected](Person.class)!public class Person_ {! public static volatile SingularAttribute<Person,Long> id;! public static volatile SingularAttribute<Person,String> name;! public static volatile SingularAttribute<Person,Integer> age;!}!
Person Entity にたいする Metamodel (Person_)
統合開発環境で自動生成されるMetamodel
![Page 53: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/53.jpg)
53 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Metamodel クラスを利用して実装した例
EntityManager em = … ;! CriteriaBuilder cb = em.getCriteriaBuilder();! CriteriaQuery<Person> p = cb.createQuery(Person.class);! Root<Person> person = p.from(Person.class);! p.select(person).! where(cb.equal(person.get(Person_.name),”Taro Yamada”));!
Person_.name は属性名でコンパイラがチェック可能 仮に Person_.nema と入力した場合コンパイルエラーが発生 これによりランタイムエラーの発生頻度を抑制可能
![Page 54: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/54.jpg)
54 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
実際に作って 見ましょう
![Page 55: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/55.jpg)
55 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
NetBeans 7.0 or 7.1
![Page 56: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/56.jpg)
56 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
サービス→JavaDBの確認(GlassFish付属のDB)
![Page 57: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/57.jpg)
57 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
新規Mavenプロジェクト生成
![Page 58: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/58.jpg)
58 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
新規Mavenプロジェクト生成
![Page 59: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/59.jpg)
59 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 60: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/60.jpg)
60 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 61: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/61.jpg)
61 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 62: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/62.jpg)
62 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 63: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/63.jpg)
63 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 64: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/64.jpg)
64 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 65: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/65.jpg)
65 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 66: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/66.jpg)
66 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
既存DBからEntityを自動生成
![Page 67: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/67.jpg)
67 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
自動生成されたPersistenceUnitの確認(persistence.xml)
![Page 68: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/68.jpg)
68 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
PersistenceUnit 名の変更
jp.co.oracle.jpa_JPAWebApplication_war_1.0-SNAPSHOTPUから JPA_SAMPLE_PUに変更
![Page 69: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/69.jpg)
69 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity からセッション Bean の作成
![Page 70: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/70.jpg)
70 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity からセッション Bean の作成
![Page 71: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/71.jpg)
71 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity からセッション Bean の作成
![Page 72: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/72.jpg)
72 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
自動生成された AbstractFacade
コンテナ管理のトランザクションのため プログラムによるトランザクション制御は不要
![Page 73: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/73.jpg)
73 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
自動生成された CustomerFacade
![Page 74: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/74.jpg)
74 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
JPA 2.1 マルチテナンシー • インスタンス・レベル • スキーマ・レベル • レコード(同一テーブル)・レベル
Linda DeMichie (Java EE Spec Lead)
![Page 75: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/75.jpg)
75 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Eclipse Link 2.3 (Indigo) Multi Tenancy Support
@Multitenant @TenantDiscriminatorColumn
![Page 76: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/76.jpg)
76 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
テナントID : Oracle テナントID : Foo
JPA におけるマルチテナンシーの1例
同一アプリケーション
![Page 77: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/77.jpg)
77 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Entity クラス
![Page 78: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/78.jpg)
78 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
アプリケーションのコピー&テナントIDの変更
テナント A 用の設定
テナント B 用の設定 アプリケーションの実装コードは 一切変更無し
![Page 79: The detail of JPA 20](https://reader034.vdocuments.site/reader034/viewer/2022051818/54b6e8b64a7959aa3d8b4752/html5/thumbnails/79.jpg)
79 | Copyright © 2011, Oracle and/or it’s affiliates. All rights reserved.
Java Persistence API の詳細ついて 日本オラクル Fusion Middleware 製品事業統括本部 シニア Java エバンジェリスト 寺田 佳央 (http://yoshio3.com)