12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 4 ■ MANAGING PERSISTENT OBJECTSManipulating EntitiesThe entity manager is also used to create complex JPQL queries to retrieve an entity or a list of entities.When manipulating single entities, the EntityManager interface can be seen as a generic Data AccessObject (DAO), which allows CRUD operations on any entity (see Table 4-1).Table 4-1. EntityManager Interface Methods to Manipulate EntitiesMethodvoid persist(Object entity) T find(Class entityClass, ObjectprimaryKey) T getReference(ClassentityClass, Object primaryKey)void remove(Object entity) T merge(T entity)void refresh(Object entity)void flush()void clear()void detach(Object entity)boolean contains(Object entity)DescriptionMakes an instance managed and persistentSearches for an entity of the specified class and primarykeyGets an instance, whose state may be lazily fetchedRemoves the entity instance from the persistencecontext and from the underlying databaseMerges the state of the given entity into the currentpersistence contextRefreshes the state of the instance from the database,overwriting changes made to the entity, if anySynchronizes the persistence context to the underlyingdatabaseClears the persistence context, causing all managedentities to become detachedRemoves the given entity from the persistence context,causing a managed entity to become detachedChecks whether the instance is a managed entityinstance belonging to the current persistence contextTo gain a better understanding of these methods, I will use a simple example of a one-way, one-toonerelationship between a Customer and an Address. Both entities have automatically generatedidentifiers (thanks to the @GeneratedValue annotation), and Customer (see Listing 4-7) has a lazy fetch toAddress (see Listing 4-8).132

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!