顯示具有 JPA 標籤的文章。 顯示所有文章
顯示具有 JPA 標籤的文章。 顯示所有文章

2017年2月25日 星期六

N + 1 selects problem

假設有User,Country,Image等Entity,如下:
<<Table>>
IMAGE
ID <<PK>>
USERID <<FK>>
NAME
TYPE
DATA
                   
<<Table>>
USER
ID <<PK>>
COUNTRYID <<FK>>
USERNAME
                   
<<Table>>
COUNTRY
ID <<PK>>
NAME
CAPITAL
Java Class:
如果透過以下的方式存取:
那麼會先產生一個SELECT來load USER entity,
之後要iterates每個user以取得country,
因此總共會產生一個(來自query User),再加上N(視你的User總共有多少個)SELECT
如果已經事先知道一定會取的每個user中的country,那麼這種做法是很沒有效率的。
另外在Lazily loaded collections也是會發生同樣的問題:

2017年2月21日 星期二

開始Hibernate (Bootstrapping Hibernate)

Persistence:在Java中提到persistence的話,通常是指透過SQL將object instance對應並存放到database中。

Bootstrapping表示初始化並且開始一個software component

Hibernate中,分別有JPA BootstrappingNative Bootstrapping(建議使用JPA-standardized bootstrapping)

JPA Bootstrapping的方式
JPA的方式中最後目標是要建立javax.persistence.EntityManagerFactory instance
在JPA標準中定義了兩種bootstrapping,分別是EE,與SE
  • EE bootstrapping,指的是manage and inject the persistence context on behalf of the application.
  • SE bootstrapping,指的是everything else
而在Hibernate中使用container-bootstrapping 以及 application-bootstrapping兩個術語(term)來表示。

另外在JPA 2.1 specification中的7.6 7.7有說明使用EntityManager instances的細節。

Container-bootstrapping中,container會為每個定義在META-INF/persistence.xml configuration file中的persistent-unit建立一個EntityManagerFactory然後讓application能夠透過注入(injection)javax.persistence.PersistenceUnit annotation或是透過JNDI的方式使用。

Application-bootstrappingapplication要透過 javax.persistence.Persistence 來建立EntityManagerFactory

可以透過entityManager instance的unwrap()使用provider(也就是Hibernate)API。

META-INF/persistence.xml檔: 使用EntityManager

source: https://github.com/readStudy/Hibernate-ORM-Study/tree/master/SetUpHibernateOrm
Reference: http://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html

2017年1月17日 星期二

mappedBy的用途

mappedBy的用途
在雙向關聯(bidirectional relationship)時,
兩方之中只有一方會是擁有者(owner),擁有者必須要負起更新,
刪除association columns等的責任,
而mappedBy attribute可以用來指出兩方關係中誰不是擁有者,
mappedBy refers to the property name of the association on the owner side。

例子:雙向的One to Many與Many to One

Reference:
  https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html
  http://stackoverflow.com/questions/11938253/jpa-joincolumn-vs-mappedby