Enterprise Java Development@TOPIC@
boolean contains(Object entity);
Returns true if object is managed in the persistence context
void clear();
Clears all entities and queued changes from the persistence context
All entities become detached
em.persist(author);
//callers can detach entity from persistence context
logger.debug("em.contains(author)={}", em.contains(author));
logger.debug("detaching author");
em.getTransaction().begin();
em.flush();
em.detach(author);
logger.debug("em.contains(author)={}", em.contains(author));
em.getTransaction().commit();
//changes to detached entities do not change database
author.setFirstName("foo");
em.getTransaction().begin();
em.getTransaction().commit();
Author author2 = em.find(Author.class, author.getId());
logger.debug("author.firstName={}", author.getFirstName());
logger.debug("author2.firstName={}", author2.getFirstName());
assertNotEquals("unexpected name change", author.getFirstName(), author2.getFirstName());
-em.contains(author)=true -detaching author -em.contains(author)=false -author.firstName=foo -author2.firstName=dr
Detaches existing entity from persistence context
Detach cascaded to CascadeType.DETACH and ALL relationships
Subsequent changes to entity will not change database
Portable use requires call to flush() prior to detach()
New entities are ignored
Author author = new Author();
logger.debug("em.contains(author)={}", em.contains(author));
logger.debug("detaching author");
em.detach(author);
logger.debug("em.contains(author)={}", em.contains(author));
-em.contains(author)=false -detaching author -em.contains(author)=false
Detached entities are ignored
Author author = new Author();
...
em.persist(author);
em.getTransaction().begin();
em.getTransaction().commit();
//detaching detached entity will be ignored
Author detached = new Author(author.getId());
logger.debug("em.contains(author)={}", em.contains(detached));
logger.debug("detaching detached author");
em.detach(detached);
logger.debug("em.contains(author)={}", em.contains(detached));
-em.contains(author)=false -detaching detached author -em.contains(author)=false