Managing Entities - The Java EE 6 Tutorial (original) (raw)

Document Information

Preface

Part I Introduction

1. Overview

2. Using the Tutorial Examples

Part II The Web Tier

3. Getting Started with Web Applications

4. JavaServer Faces Technology

5. Introduction to Facelets

6. Expression Language

7. Using JavaServer Faces Technology in Web Pages

8. Using Converters, Listeners, and Validators

9. Developing with JavaServer Faces Technology

10. JavaServer Faces Technology: Advanced Concepts

11. Using Ajax with JavaServer Faces Technology

12. Composite Components: Advanced Topics and Example

13. Creating Custom UI Components and Other Custom Objects

14. Configuring JavaServer Faces Applications

15. Java Servlet Technology

16. Uploading Files with Java Servlet Technology

17. Internationalizing and Localizing Web Applications

Part III Web Services

18. Introduction to Web Services

19. Building Web Services with JAX-WS

20. Building RESTful Web Services with JAX-RS

21. JAX-RS: Advanced Topics and Example

Part IV Enterprise Beans

22. Enterprise Beans

23. Getting Started with Enterprise Beans

24. Running the Enterprise Bean Examples

25. A Message-Driven Bean Example

26. Using the Embedded Enterprise Bean Container

27. Using Asynchronous Method Invocation in Session Beans

Part V Contexts and Dependency Injection for the Java EE Platform

28. Introduction to Contexts and Dependency Injection for the Java EE Platform

29. Running the Basic Contexts and Dependency Injection Examples

30. Contexts and Dependency Injection for the Java EE Platform: Advanced Topics

31. Running the Advanced Contexts and Dependency Injection Examples

Part VI Persistence

32. Introduction to the Java Persistence API

Entities

Requirements for Entity Classes

Persistent Fields and Properties in Entity Classes

Persistent Fields

Persistent Properties

Using Collections in Entity Fields and Properties

Validating Persistent Fields and Properties

Primary Keys in Entities

Multiplicity in Entity Relationships

Direction in Entity Relationships

Bidirectional Relationships

Unidirectional Relationships

Queries and Relationship Direction

Cascade Operations and Relationships

Orphan Removal in Relationships

Embeddable Classes in Entities

Entity Inheritance

Abstract Entities

Mapped Superclasses

Non-Entity Superclasses

Entity Inheritance Mapping Strategies

The Single Table per Class Hierarchy Strategy

The Table per Concrete Class Strategy

The Joined Subclass Strategy

Querying Entities

Further Information about Persistence

33. Running the Persistence Examples

34. The Java Persistence Query Language

35. Using the Criteria API to Create Queries

36. Creating and Using String-Based Criteria Queries

37. Controlling Concurrent Access to Entity Data with Locking

38. Using a Second-Level Cache with Java Persistence API Applications

Part VII Security

39. Introduction to Security in the Java EE Platform

40. Getting Started Securing Web Applications

41. Getting Started Securing Enterprise Applications

42. Java EE Security: Advanced Topics

Part VIII Java EE Supporting Technologies

43. Introduction to Java EE Supporting Technologies

44. Transactions

45. Resources and Resource Adapters

46. The Resource Adapter Example

47. Java Message Service Concepts

48. Java Message Service Examples

49. Bean Validation: Advanced Topics

50. Using Java EE Interceptors

Part IX Case Studies

51. Duke's Bookstore Case Study Example

52. Duke's Tutoring Case Study Example

53. Duke's Forest Case Study Example

Index

Entities are managed by the entity manager, which is represented by javax.persistence.EntityManagerinstances. Each EntityManager instance is associated with a persistence context: a set of managed entity instances that exist in a particular data store. A persistence context defines the scope under which particular entity instances are created, persisted, and removed. The EntityManager interface defines the methods that are used to interact with the persistence context.

The EntityManager Interface

The EntityManager API creates and removes persistent entity instances, finds entities by the entity’s primary key, and allows queries to be run on entities.

Container-Managed Entity Managers

With a container-managed entity manager, an EntityManager instance’s persistence context is automatically propagated by the container to all application components that use the EntityManager instance within a single Java Transaction API (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 when an EntityManager is injected into the application components by means of the javax.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 to the persistence context within that transaction. By automatically propagating the persistence context, application components don’t need to pass references to EntityManager instances to each other in order to make changes within a single transaction. The Java EE container manages the lifecycle of container-managed entity managers.

To obtain an EntityManager instance, inject the entity manager into the application component:

@PersistenceContext EntityManager em;

Application-Managed Entity Managers

With an application-managed entity manager, on the other hand, the persistence context is not propagated to application components, and the lifecycle of EntityManager instances is managed by the application.

Application-managed entity managers are used when applications need to access a persistence context that is not propagated with the JTA transaction across EntityManager instances in a particular persistence unit. In this case, each EntityManager creates a new, isolated persistence context. The EntityManager and its associated persistence context are created and destroyed explicitly by the application. They are also used when directly injecting EntityManager instances can’t be done because EntityManager instances are not thread-safe. EntityManagerFactory instances are thread-safe.

Applications create EntityManager instances in this case by using the createEntityManager method of javax.persistence.EntityManagerFactory.

To obtain an EntityManager instance, you first must obtain an EntityManagerFactory instance by injecting it into the application component by means of the javax.persistence.PersistenceUnit annotation:

@PersistenceUnit EntityManagerFactory emf;

Then obtain an EntityManager from the EntityManagerFactory instance:

EntityManager em = emf.createEntityManager();

Application-managed entity managers don’t automatically propagate the JTA transaction context. Such applications need to manually gain access to the JTA transaction manager and add transaction demarcation information when performing entity operations. The javax.transaction.UserTransaction interface defines methods to begin, commit, and roll back transactions. Inject an instance of UserTransaction by creating an instance variable annotated with @Resource:

@Resource UserTransaction utx;

To begin a transaction, call the UserTransaction.begin method. When all the entity operations are complete, call the UserTransaction.commit method to commit the transaction. The UserTransaction.rollbackmethod is used to roll back the current transaction.

The following example shows how to manage transactions in an application that uses an application-managed entity manager:

@PersistenceContext EntityManagerFactory emf; EntityManager em; @Resource UserTransaction utx; ... em = emf.createEntityManager(); try { utx.begin(); em.persist(SomeEntity); em.merge(AnotherEntity); em.remove(ThirdEntity); utx.commit(); } catch (Exception e) { utx.rollback(); }

Finding Entities Using the EntityManager

The EntityManager.find method is used to look up entities in the data store by the entity’s primary key:

@PersistenceContext EntityManager 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 Lifecycle

You manage entity instances by invoking operations on the entity by means of an EntityManager instance. Entity instances are in one of four states: new, managed, detached, or removed.

Persisting Entity Instances

New entity instances become managed and persistent either by invoking the persist method or by a cascading persist operation invoked from related entities that have thecascade=PERSIST or cascade=ALL elements set in the relationship annotation. This means that the entity’s data is stored to the database when the transaction associated with thepersist operation is completed. If the entity is already managed, the persist operation is ignored, although the persist operation will cascade to related entities that have thecascade element set to PERSIST or ALL in the relationship annotation. If persistis called on a removed entity instance, the entity becomes managed. If the entity is detached, either persist will throw an IllegalArgumentException, or the transaction commit will fail.

@PersistenceContext EntityManager 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; }

The persist operation is propagated to all entities related to the calling entity that have the cascade element set to ALL or PERSIST in the relationship annotation:

@OneToMany(cascade=ALL, mappedBy="order") public Collection getLineItems() { return lineItems; }

Removing Entity Instances

Managed entity instances are removed by invoking the remove method or by a cascading remove operation invoked from related entities that have the cascade=REMOVE or cascade=ALLelements set in the relationship annotation. If the remove method is invoked on a new entity, the remove operation is ignored, although remove will cascade to related entities that have the cascade element set to REMOVE or ALL in the relationship annotation. If remove is invoked on a detached entity, either remove will throw an IllegalArgumentException, or the transaction commit will fail. If invoked on an already removed entity, remove will be ignored. The entity’s data will be removed from the data store when the transaction is completed or as a result of the flush operation.

public void removeOrder(Integer orderId) { try { Order order = em.find(Order.class, orderId); em.remove(order); }...

In this example, all LineItem entities associated with the order are also removed, as Order.getLineItems has cascade=ALL set in the relationship annotation.

Synchronizing Entity Data to the Database

The state of persistent entities is synchronized to the database when the transaction with which the entity is associated commits. If a managed entity is in a bidirectional relationship with another managed entity, the data will be persisted, based on the owning side of the relationship.

To force synchronization of the managed entity to the data store, invoke theflush method of the EntityManager instance. If the entity is related to another entity and the relationship annotation has the cascade element set to PERSIST orALL, the related entity’s data will be synchronized with the data store whenflush is called.

If the entity is removed, calling flush will remove the entity data from the data store.

Persistence Units

A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application. This set of entity classes represents the data contained within a single data store.

Persistence units are defined by the persistence.xml configuration file. The following is an example persistence.xml file:

This unit manages orders and customers. It does not rely on any vendor-specific features and can therefore be deployed to any persistence provider. jdbc/MyOrderDB MyOrderApp.jar com.widgets.Order com.widgets.Customer

This file defines a persistence unit named OrderManagement, which uses a JTA-aware data source: jdbc/MyOrderDB. The jar-file and class elements specify managed persistence classes: entity classes, embeddable classes, and mapped superclasses. The jar-file element specifies JAR files that are visible to the packaged persistence unit that contain managed persistence classes, whereas the class element explicitly names managed persistence classes.

The jta-data-source (for JTA-aware data sources) and non-jta-data-source (for non-JTA-aware data sources) elements specify the global JNDI name of the data source to be used by the container.

The JAR file or directory whose META-INF directory contains persistence.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 to the persistence unit’s scope.

Persistent units can be packaged as part of a WAR or EJB JAR file or can be packaged as a JAR file that can then be included in an WAR or EAR file.

Previous Contents Next

Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Legal Notices