21 4月 2010

JPA2--Entity Manager (1)

Entity Manager 藉由Persistence Context來控制被管理的Entity Instances,而每個Persistence Context必定由一個Persistence Unit來限制該Context可以管理的Entity Classes種類。

Entity Manager 可以分為兩類

  • Container-Managed Entity Manager
  • Application-Managed Entity Manager
Container-Managed Entity Manager(以下簡稱CMEM)就如同字意上所代表的,是由JEE Container所管理的Entity Manager,主要是以@PersistenceContext標識在你的程式中,Container會在執行期間自動注入對應的instance。CMEM還可以再區分兩類:PersistenceContextType.TRANSACTION (Default)及 PersistenceContextType.EXTENDED

TRANSACTION:主要是配合Stateless Session Bean與JTA Transaction,在每次CMEM的method被呼叫時都去檢查JTA transaction中是不是有Persistence Context,如果有就續用否則就建一個新的。當JTA Transaction commit 時,在persistence context中的entity instances就會自動persist至DB。

EXTENDED:主要是配合Stateful Session Bean,只有當執行到有@Remove標識的method時才會persist 在persistence context中的entity instances。

Application-Managed Entity Manager(以下簡稱AMEM)也很清楚,就是由Application自行管理,藉由呼叫EntityManagerFactory.createEntityManager()來取得AMEM,也因為如此,一般的J2SE程式也可以使用,當然在JEE Container也可以使用,特別是在某些特別情況或有特殊考慮時多一種方式可以應用。如果要在JEE Container中使用的話,與CMEM不同之處是以@PersistenceUnit來標識要被注入的EntityManagerFactory,而且也必需呼叫EntityManager.close()來指出要persist的時機。AMEM產生persistence context的時機也與CMEM有所不同,當呼叫EntityManagerFactory.createEntityManager()就會產生一個persistence context。

不過Transaction並不是只有這麼簡單....


沒有留言: