Java persistence api最早是EJB的一部分,在EJB3時候被分離出來JPA1.0,之後出現了JPA2.0、2.1。不同公司發佈了Hibernate, Eclipselink, Toplink, Spring Data JPA等。
Generally, Java developers use lots of code, or use the proprietary framework to interact with the database, whereas using JPA, the burden of interacting with the database reduces significantly. It forms a bridge between object models (Java program) and relational models (database program).
JPA用來將業務邏輯和數據庫的邏輯聯繫起來。簡單說來,數據庫包括的數據源和數據操作都可以採用java級別的code表現出來。
Database級別表示 | Java應用級別表示 | 描述 |
---|---|---|
Source data | Entity | 持久化對象 |
Read, Update, Delete | Query, EntityManager | 屬於DAO層 |
Save | Persistence | 靜態獲取EntityManagerFactory的實例 |
Transaction | EntityManagerFactory, Entity transaction, | service層 |
現在問題來了,如果對象之間存在繼承(Inheritance)關係,那是不是就必須要見不同的表呢?這時就需要在給父類加上繼承策略(共有三種:SINGLE_TABLE、JOINED_TABLE、TABLE_PER_CONCRETE_CLASS)
用法如下:
@Inheritance( strategy = “你選擇的繼承策略”)
@Entity
@Table
@Inheritance( strategy = InheritanceType.TABLE_PER_CLASS )
public class Parent implements Serializable {
//
}
Child class
@Entity
@Table
public class Child extends Parent {
//
}
- Single Table strategy
所有的列都會存到同一張表裏面; - Table per class strategy
這個很好理解,一張表對應一個class,有多少個child class就創建多少張表; - Joined table Strategy
創建parent和多張child class表,但是parent外鍵對應子表的主鍵。