df074406fa90c11062a1487d04256c99.ppt
- Количество слайдов: 43
Enterprise Java Persistence: Entity. Manager
Goals Enterprise Java • Become familiar with the Java Persistence Entity. Manager – API – Provider • Hibernate v 070903 Java Persistence: Entity. Manager 2
Overview Enterprise Java • Earlier versions of EJB Specification defined the persistence layer – javax. ejb. Entity. Bean • Java EE 5 has moved persistence to its own specification – javax. persistence API (1. 0) • ease of use API above JDBC • Provides – Object/Relational Mapping (ORM) Engine – Query Language (SQL-Like, based on former EJB-QL) v 070903 Java Persistence: Entity. Manager 3
javax. persistence. Entity. Manager Enterprise Java • Replaces much of the EJB 2. x “Home” functionality • Handles O/R Mapping of Entities to the database • Provides APIs – – inserting objects into database getting objects from database synchronizing objects with database querying database • Provides caching • Coordinates with transactional services (JTA) • Tightly integrated with Java EE and EJB, but not limited to that environment v 070903 Java Persistence: Entity. Manager 4
Entities Enterprise Java • (formerly and sometimes still called Entity Beans) • are now Plain Old Java Objects (POJOs) – nothing special happens when calling new Author author = new Author(); • are not persistent until associated with an Entity. Manager em. persist(author); v 070903 Java Persistence: Entity. Manager 5
Example Author POJO Entity Enterprise Java @javax. persistence. Entity public class Author { private long id; private long version=0; private String first. Name; private String last. Name; private String subject; private Date publish. Date; public Author() {} public Author(long id) { this. id = id; } . . . } v 070903 @Id @Generated. Value public long get. Id() { return id; } private void set. Id(long id) { this. id = id; } public String get. First. Name() { return first. Name; } public void set. First. Name(String first. Name) { this. first. Name = first. Name; } Java Persistence: Entity. Manager 6
Creating Entity in Database Enterprise Java log_. info("test. Create()"); Author author = new Author(); //primary key will be gen author. set. First. Name("dr"); author. set. Last. Name("seuss"); author. set. Subject("children"); author. set. Publish. Date(new Date()); log_. info("creating author: " + author); em. persist(author); log_. info("created author: " + author); //output -creating author: id=0, fn=dr, pdate=Fri Sep 15 11: 54: 15 EDT -created author: id=50, fn=dr, pdate=Fri Sep 15 11: 54: 15 EDT v 070903 ln=seuss, subject=children, 2006 Java Persistence: Entity. Manager 7
Managed and Unmanaged Entities Enterprise Java • Unmanaged state (detached) – instance not associated with an Entity. Manager – state changes are not tracked – can be serialized to client and returned to be synchronized with database – nothing equivalent to this state in EJB 2. 1 entity beans • Managed state (attached) – instance associated with an Entity. Manager – state changes are tracked within a Persistence Context – EJB 2. 1 entity beans were always managed • client interfaced with data through a proxy or state transferred through a Data Transfer Object v 070903 Java Persistence: Entity. Manager 8
Persistence Context Enterprise Java • A set of attached entity instances managed by an Entity. Manager • All entities become detached once closed • Two types – Transaction-scoped Persistence Contexts • begin/end at transaction boundaries • only made available through container managed persistence contexts – Extended Persistence Contexts • live beyond any single transaction • allow longer-lived interactions with database without lengthy transactions tying up database resources v 070903 Java Persistence: Entity. Manager 9
Persistence Context Examples Enterprise Java • Transaction-scoped (inside server container) @Persistence. Context(unit. Name=”jpa. Demo”) Entity. Manager em; @Transaction. Attribute(REQUIRED) public void update(long author. Id, String type) { Author author = em. find(Author. class, author. Id); author. set. Type(type); } • Extended (inside or outside server container) Entity. Manager em = Persistence. create. Entity. Manager. Factory(“jpa. Demo”). create. Entity. Manager(); tx. begin(); //tx 1 begins Author author = em. find(Author. class, author. Id); tx. commit(); //tx 1 ends, but author remains managed. . . tx. begin(); //tx 2 begins author. set. Type(type); tx. commit(); //tx 2 ends, and author is still managed until close v 070903 Java Persistence: Entity. Manager 10
Persistence Unit Enterprise Java • A set of classes that are mapped to the database • defined in META-INF/persistence. xml • must have an identity – “” is a valid identity • Classes – may be named in persistence. xml file – may be automatically scanned for in the classpath • orm. xml – optionally provided to augment, provide, or replace class persistence metadata – (more on orm. xml in Core ORM topic) v 070903 Java Persistence: Entity. Manager 11
Example Component Layout Enterprise Java META-INF/ +---persistence. xml ejava + ---examples +---dao +---DAOException. class +---Author. DAO. class +---jpa | +---JPAAuthor. DAO. class | +---JPADAOBase. class +--domain +---Author. class v 070903 Java Persistence: Entity. Manager 12
persistence. xml elements • • • Enterprise Java name – identity to reference Persistence Unit provider – fully qualified name of javax. persistence. Provider – not needed if provider found in classpath acceptable mapping-file – resource path to optional mapping file – can be used to specify
" src="https://present5.com/presentation/df074406fa90c11062a1487d04256c99/image-16.jpg" alt="Specifying an optional orm. xml file Enterprise Java xml version="1. 0" encoding="UTF-8"? >" />
Specifying an optional orm. xml file Enterprise Java xml version="1. 0" encoding="UTF-8"? >
Entities Discovered Enterprise Java • classes with @Entity annotation – in the persistence. xml's JAR file – contained in any JAR file listed in jar-file element • classes mapped – with META-INF/orm. xml – with custom mapping files • classes listed in persistence. xml's “
Java SE Steps Enterprise Java • Startup – Get Entity. Manager. Factory • Runtime – – – Create Entity. Manager Start Transaction Interact with Entity Manager Commit Transaction Close Entity. Manager • Shutdown – Close Entity. Manager. Factory v 070903 Java Persistence: Entity. Manager 19
javax. persistence. Persistence Enterprise Java • used to bootstrap persistence in Java SE environments public class javax. persistence. Persistence { public static java. lang. String PERSISTENCE_PROVIDER; public javax. persistence. Persistence(); public static Entity. Manager. Factory create. Entity. Manager. Factory(String pu. Name, Map props); } • example usage Entity. Manager. Factory emf = Persistence. create. Entity. Manager. Factory(“jpa. Demo”); v 070903 Java Persistence: Entity. Manager 20
Enterprise Java javax. persistence. Entity. Manager. Factory • used to obtain reference to Entity. Manager in standard Java SE environments package javax. persistence; public interface Entity. Manager. Factory{ Entity. Manager create. Entity. Manager(); Entity. Manager create. Entity. Manager(Map props); void close(); boolean is. Open(); } • Map used to supply or override properties in persistence. xml • close() and is. Open() only valid for non-injected EMFs • example usage – Entity. Manager em = emf. create. Entity. Manager. Factory(); v 070903 Java Persistence: Entity. Manager 21
javax. persistence. Entity. Manager Enterprise Java package javax. persistence; public interface Entity. Manager{ Entity. Transaction get. Transaction(); void persist(java. lang. Object); Object
persist() Enterprise Java Author author = new Author(next. Id()); author. set. First. Name("dr"); author. set. Last. Name("seuss"); author. set. Subject("children"); author. set. Publish. Date(new Date()); em. persist(author); • Extended persistence contexts – queues write until associated with transaction • Transaction-scoped persistence contexts – illegal to call outside the scope of a transaction • Actual write to the database depends on Flush. Mode – manually controlled with flush() call v 070903 Java Persistence: Entity. Manager 23
find() Enterprise Java Author author 2=null; author 2 = em. find(Author. class, id); log_. info("got author: " + author 2); got author: id=51, fn=thing, ln=one, subject=children, pdate=Fri Sep 15 11: 54: 15 EDT 2006 • Returns an instance of the class associated with the specified primary key value – relationships are instantiated according to lazy-loading policies • Returns null if primary key not found • Uses generics, so no casting is necessary • Ids can be autoboxed without a manual wrapper • can be called outside the scope of a transaction • will be attached to open persistence context – second find() will return same object v 070903 Java Persistence: Entity. Manager 24
get. Reference() Enterprise Java Author author 2=null; author 2 = em. get. Reference(Author. class, id); log_. info("got author: " + author 2); • Similar to find() – Returns an instance of the class associated with the specified primary key value • no guarantee that object state initialized – Throws Entity. Not. Found. Exception if primary key not found v 070903 Java Persistence: Entity. Manager 25
create. Query() Enterprise Java • 5 create. Query() methods Query Query create. Query(String ejbql. String); create. Named. Query(String name); create. Native. Query(String sql. String, Class result. Class); create. Native. Query(String sql. String, String result. Set. Map); • example usage Query query = em. create. Query("from jpa. Author where id=" + id); Author author = (Author)query. get. Single. Result(); • use EJB-QL and native (SQL) query languages • similar to find/get. Reference() –returned objects attached to open persistence context v 070903 Java Persistence: Entity. Manager 26
updating entities Enterprise Java • Updates to managed entities automatically get propagated to database according to flush policy public Author update(Author author) { Author db. Author = em. find(Author. class, author. get. Id()); db. Author. set. First. Name(author. get. First. Name()); db. Author. set. Last. Name(author. get. Last. Name()); db. Author. set. Subject(author. get. Subject()); db. Author. set. Publish. Date(author. get. Publish. Date()); return db. Author; } v 070903 Java Persistence: Entity. Manager 27
merge() Enterprise Java • merges state changes to detached objects back into persistent storage public Author update. By. Merge(Author author) { Author managed. Author = em. merge(author); return managed. Author; } • Original is left detached • Object returned is managed • Returned object is added to persistence if did not already exist • Updates are made to existing object if already exists v 070903 Java Persistence: Entity. Manager 28
remove() Enterprise Java public void remove(Author author) { em. remove(author); } – removes object from database • physically performed in database according to flush policy • cascades to related objects according to cascade policy – object will be detached v 070903 Java Persistence: Entity. Manager 29
refresh() and contains() • refresh() Enterprise Java Author author = em. find(Author. class, id); em. refresh(author); – used to make sure entity is in sync with database • cascades to related entities depending on cascade policy – entity must be currently managed by entity manager instance • contains() if (em. contains(author)) {. . . } – used to test if instance is being managed by entity manager instance v 070903 Java Persistence: Entity. Manager 30
clear() and flush() • • Enterprise Java clear() – detaches all entities – does not commit queued changes • call flush() prior to clear() flush() – changes not synchronized with database until entity manager flushed • persist(), merge(), remove() – occurs automatically before executing • correlated queries – permits query to reflect changes in persistence context • transaction commit – not impacted by primary key finders • find(), get. Reference() – Flush. Mode • AUTO – default and most sane • COMMIT – an optimization to only flush and end of transaction. May limit amount of database locking that occurs v 070903 Java Persistence: Entity. Manager 31
lock() and get. Delegate() Enterprise Java • lock() – provides a pessimistic write lock for entity – will be covered with later during transaction topics • get. Delegate() – returns vendor object that implements Entity. Manager interface – used to expose vendor-specific extension API v 070903 Java Persistence: Entity. Manager 32
Entity. Transactions Enterprise Java • Only available for Entity Managers with an extended persistence context – Transaction-scoped persistence contexts are only available with containers that support JTA transactions – Extended persistence contexts generally pertain to Java SE applications using javax. persistence. Persistence class to get Entity. Manager. Factory • transaction-like API for managing transactions within the single resource • transaction context obtained from Entity. Manager javax. persistence. Entity. Transaction tx = em. get. Transaction(); tx. begin() tx. commit() tx. is. Active() tx. rollback() v 070903 Java Persistence: Entity. Manager 33
Example Enterprise Java private Entity. Manager em =. . . public void test. Query() throws Exception { Author author = new Author(); author. set. First. Name("test"); author. set. Last. Name("Query"); author. set. Subject("testing"); author. set. Publish. Date(new Date()); em. persist(author); //need to associate em with Tx to allow query to see entity in DB try { em. get. Transaction(). begin(); //note that the persist does not have to be within the tx em. get. Transaction(). commit(); } catch (Exception ex) { em. get. Transaction(). rollback(); fail("" + ex); } Author author 2 = null; Query query = em. create. Query( "from jpa. Author where id=" + author. get. Id()); author 2 = (Author)query. get. Single. Result(); } v 070903 assert. Not. Null(author 2); assert. Equals(author. get. First. Name(), author 2. get. First. Name()); assert. Equals(author. get. Last. Name(), author 2. get. Last. Name()); assert. Equals(author. get. Subject(), author 2. get. Subject()); assert. Equals(author. get. Publish. Date(), author 2. get. Publish. Date()); Java Persistence: Entity. Manager 34
Enterprise Java Hibernate Persistence Container v 070903 Java Persistence: Entity. Manager 35
Classpath • • Enterprise Java hibernate. jar hibernate-annotations. jar hibernate-entitymanager. jat third party jars – automatically downloaded with maven – can also get them using the thirdparty-all. jar that is distributed with the JBoss embeddable container v 070903 Java Persistence: Entity. Manager 36
Enterprise Java Example Hibernate Maven Dependencies
JPAUtil. java Enterprise Java package ejava. examples. dao. jpa; import java. util. Hash. Map; java. util. Map; javax. persistence. Entity. Manager. Factory; javax. persistence. Persistence; public class JPAUtil { private static final Map
JUnit Setup Enterprise Java public class All. Test extends Test. Case { private static Log log_ = Log. Factory. get. Log(All. Test. class); public static Test suite() { Test. Suite tests = new Test. Suite(); tests. add. Test. Suite(JPAExtended. Only. Demo. class); Test. Setup wrapper = new Test. Setup(tests) { //one-time setup public void set. Up() throws Exception { } //one-time tear down public void tear. Down() throws Exception { JPAUtil. close(); } }; } v 070903 return wrapper; Java Persistence: Entity. Manager 39
JUnit Tests Enterprise Java public class JPAExtended. Only. Demo extends Test. Case { private Entity. Manager em; public void set. Up() throws Exception { Entity. Manager. Factory emf = JPAUtil. get. Entity. Manager. Factory(“jpa. Demo”); em = emf. create. Entity. Manager(); } public void tear. Down() throws Exception { em. get. Transaction(). begin(); em. flush(); em. close(); em. get. Transaction(). commit(); } public void test. Create() throws Exception { Author author = new Author(); author. set. First. Name("dr"); author. set. Last. Name("seuss"); author. set. Subject("children"); author. set. Publish. Date(new Date()); } v 070903 em. persist(author); Java Persistence: Entity. Manager 40
Build and Test Environment Enterprise Java
Summary • • Enterprise Java Persistence API – Java standard for mapping objects to relational databases – currently part of Java EE; will be in Java SE 6 – eliminates the need or desire for EJB 2. 1 entity Entity – a POJO – operates both detached and managed by OR Mapping Persistence Unit – a set of entity classes mapped to the database schema Persistence Context – a set of objects that managed – Transaction-scoped or Extended javax. persistence. Entity. Manager – manages objects in a persistence context javax. persistence. Entity. Manager. Factory – used to create individual entity managers javax. persistence. Persistence – used to bootstrap Entity. Manager. Factory into Java SE applications v 070903 Java Persistence: Entity. Manager 42
References Enterprise Java • “Enterprise Java. Beans 3. 0, 5 th Edition”; Burke & Monsen-Haefel; ISBN 0 -596 -00978 -X; O'Reilly v 070903 Java Persistence: Entity. Manager 43


