2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API Requirements for Entity Classes Persistent Fields and Properties in Entity Classes Multiplicity in Entity Relationships Direction in Entity Relationships Queries and Relationship Direction Cascade Deletes and Relationships Entity Inheritance Mapping Strategies Container-Managed Entity Managers Application-Managed Entity Managers Finding Entities Using theEntityManager 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Managing EntitiesEntities are managed by the entity manager. The entity manager is represented byjavax.persistence.EntityManager instances. EachEntityManager instance is associated with a persistence context. A persistencecontext defines the scope under which particular entity instances are created, persisted, andremoved. The Persistence ContextA persistence context is a set of managed entity instances that exist ina particular data store. TheEntityManager interface defines the methods that are usedto interact with the persistence context. TheEntityManager InterfaceTheEntityManager API creates and removes persistent entity instances, finds entities by theentity’s primary key, and allows queries to be run on entities. Container-Managed Entity ManagersWith acontainer-managed entity manager, anEntityManager instance’s persistence context is automatically propagated by thecontainer to all application components that use theEntityManager instance within asingle Java Transaction Architecture (JTA) transaction. JTA transactions usually involve calls across application components. To complete a JTA transaction,these components usually need access to a single persistence context. This occurs whenanEntityManager is injected into the application components by means of thejavax.persistence.PersistenceContextannotation. The persistence context is automatically propagated with the current JTA transaction, andEntityManager references that are mapped to the same persistence unit provide access tothe persistence context within that transaction. By automatically propagating the persistence context, application componentsdon’t need to pass references toEntityManager instances to each other inorder to make changes within a single transaction. The Java EE container managesthe life cycle of container-managed entity managers. To obtain anEntityManager instance, inject the entity manager into the application component: @PersistenceContextEntityManager em; Application-Managed Entity ManagersWithapplication-managed entity managers, on the other hand, the persistence context is not propagated toapplication components, and the life cycle ofEntityManager instances is managed by the application. Application-managed entity managers are used when applications need to access a persistence contextthat is not propagated with the JTA transaction acrossEntityManager instances in aparticular persistence unit. In this case, eachEntityManager creates a new, isolated persistence context.TheEntityManager, and its associated persistence context, is created and destroyed explicitly by theapplication. Applications createEntityManager instances in this case by using thecreateEntityManager method ofjavax.persistence.EntityManagerFactory. To obtain anEntityManager instance, you first must obtain anEntityManagerFactory instance by injectingit into the application component by means of thejavax.persistence.PersistenceUnit annotation: @PersistenceUnitEntityManagerFactory emf; Then, obtain anEntityManager from theEntityManagerFactory instance: EntityManager em = emf.createEntityManager(); Finding Entities Using theEntityManagerTheEntityManager.find method is used to look up entities in the data storeby the entity’s primary key. @PersistenceContextEntityManager em;public void enterOrder(int custID, Order newOrder) { Customer cust = em.find(Customer.class, custID); cust.getOrders().add(newOrder); newOrder.setCustomer(cust);}Managing an Entity Instance’s Life CycleYou manage entity instances by invoking operations on the entity by means ofanEntityManager instance. Entity instances are in one of four states: new, managed,detached, or removed. New entity instances have no persistent identity and are not yet associated witha persistence context. Managed entity instances have a persistent identity and are associated with a persistencecontext. Detached entity instances have a persistent identify and are not currently associated witha persistence context. Removed entity instances have a persistent identity, are associated with a persistent context,and are scheduled for removal from the data store. Persisting Entity InstancesNew entity instances become managed and persistent either by invoking thepersist method,or by a cascadingpersist operation invoked from related entities that have thecascade=PERSIST orcascade=ALL elements set in the relationship annotation. This means the entity’sdata is stored to the database when the transaction associated with thepersistoperation is completed. If the entity is already managed, thepersist operation isignored, although thepersist operation will cascade to related entities that have thecascadeelement set toPERSIST orALL in the relationship annotation. Ifpersistis called on a removed entity instance, it becomes managed. If the entityis detached,persist will throw anIllegalArgumentException, or the transaction commit will fail. @PersistenceContextEntityManager em;...public LineItem createLineItem(Order order, Product product, int quantity) { LineItem li = new LineItem(order, product, quantity); order.getLineItems().add(li); em.persist(li); return li;}Thepersist operation is propagated to all entities related to the calling entitythat have thecascade element set toALL orPERSIST in the relationship annotation. @OneToMany(cascade=ALL, mappedBy="order")public Collection<LineItem> getLineItems() { return lineItems;}Removing Entity InstancesManaged entity instances are removed by invoking theremove method, or by acascadingremove operation invoked from related entities that have thecascade=REMOVE orcascade=ALLelements set in the relationship annotation. If theremove method is invoked on anew entity, theremove operation is ignored, althoughremove will cascade to relatedentities that have thecascade element set toREMOVE orALL in therelationship annotation. Ifremove is invoked on a detached entity it will throwanIllegalArgumentException, or the transaction commit will fail. Ifremove is invoked onan already removed entity, it will be ignored. The entity’s data will beremoved from the data store when the transaction is completed, or as aresult of theflush operation. public void removeOrder(Integer orderId) { try { Order order = em.find(Order.class, orderId); em.remove(order); }...In this example, allLineItem entities associated with the order are also removed,asOrder.getLineItems hascascade=ALL set in the relationship annotation. Synchronizing Entity Data to the DatabaseThe state of persistent entities is synchronized to the database when the transactionwith which the entity is associated commits. If a managed entity is ina bidirectional relationship with another managed entity, the data will be persisted basedon the owning side of the relationship. To force synchronization of the managed entity to the data store, invoke theflush method of the entity. If the entity is related to another entity,and the relationship annotation has thecascade element set toPERSIST orALL,the related entity’s data will be synchronized with the data store whenflushis called. If the entity is removed, callingflush will remove the entity data fromthe data store. Creating QueriesTheEntityManager.createQuery andEntityManager.createNamedQuery methods are used to query the datastore usingJava Persistence query language queries. SeeChapter 27, The Java Persistence Query Language for more information on the query language. ThecreateQuery method is used to createdynamic queries, queries that are defineddirectly within an application’s business logic. public List findWithName(String name) {return em.createQuery( "SELECT c FROM Customer c WHERE c.name LIKE :custName") .setParameter("custName", name) .setMaxResults(10) .getResultList();}ThecreateNamedQuery method is used to createstatic queries, queries that are definedin metadata using thejavax.persistence.NamedQuery annotation. Thename element of@NamedQuery specifies thename of the query that will be used with thecreateNamedQuery method. Thequery element of@NamedQuery is the query. @NamedQuery( name="findAllCustomersWithName", query="SELECT c FROM Customer c WHERE c.name LIKE :custName") Here’s an example ofcreateNamedQuery, which uses the@NamedQuery defined above. @PersistenceContextpublic EntityManager em;...customers = em.createNamedQuery("findAllCustomersWithName") .setParameter("custName", "Smith") .getResultList();Named Parameters in QueriesNamed parameters are parameters in a query that are prefixed with a colon(:). Named parameters in a query are bound to an argument by thejavax.persistence.Query.setParameter(String name, Object value) method. In the following example, thename argument to thefindWithName businessmethod is bound to the:custName named parameter in the query bycallingQuery.setParameter. public List findWithName(String name) { return em.createQuery( "SELECT c FROM Customer c WHERE c.name LIKE :custName") .setParameter("custName", name) .getResultList();}Named parameters are case-sensitive, and may be used by both dynamic and staticqueries. Positional Parameters in QueriesYou may alternately use positional parameters in queries, instead of named parameters. Positionalparameters are prefixed with a question mark (?) followed the numeric position ofthe parameter in the query. TheQuery.setParameter(integer position, Object value) method is used to set the parametervalues. In the following example, thefindWithName business method is rewritten to use inputparameters: public List findWithName(String name) { return em.createQuery( “SELECT c FROM Customer c WHERE c.name LIKE ?1”) .setParameter(1, name) .getResultList();}Input parameters are numbered starting from 1. Input parameters are case-sensitive, and maybe used by both dynamic and static queries. Persistence UnitsA persistence unit defines a set of all entity classes that aremanaged byEntityManager instances in an application. This set of entity classes represents thedata contained within a single data store. Persistence units are defined by thepersistence.xml configuration file. The JAR file ordirectory whoseMETA-INF directory containspersistence.xml is called the root of the persistence unit.The scope of the persistence unit is determined by the persistence unit’s root. Each persistence unit must be identified with a name that is unique tothe persistence unit’s scope. Persistent units can be packaged as part of a WAR or EJBJAR file, or can be packaged as a JAR file that can thenbe included in an WAR or EAR file. If you package the persistent unit as a set of classes inan EJB JAR file,persistence.xml should be put in the EJB JAR’sMETA-INFdirectory. If you package the persistence unit as a set of classes ina WAR file,persistence.xml should be located in the WAR file’sWEB-INF/classes/META-INFdirectory. If you package the persistence unit in a JAR file that willbe included in a WAR or EAR file, the JAR file should belocated:
Thepersistence.xml Filepersistence.xml defines one or more persistence units. The following is an examplepersistence.xmlfile. <persistence> <persistence-unit name="OrderManagement"> <description>This unit manages orders and customers. It does not rely on any vendor-specific features and can therefore be deployed to any persistence provider. </description> <jta-data-source>jdbc/MyOrderDB</jta-data-source> <jar-file>MyOrderApp.jar</jar-file> <class>com.widgets.Order</class> <class>com.widgets.Customer</class> </persistence-unit></persistence> This file defines a persistence unit namedOrderManagement, which uses a JTA-aware datasourcejdbc/MyOrderDB. Thejar-file andclass elements specify managed persistence classes: entity classes,embeddable classes, and mapped superclasses. Thejar-file element specifies JAR files thatare visible to the packaged persistence unit that contain managed persistence classes, whilethe class element explicitly names managed persistence classes. Thejta-data-source (for JTA-aware data sources) andnon-jta-data-source (non-JTA-aware data sources) elements specify theglobal JNDI name of the data source to be used by thecontainer. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |