/** * Check if the instance is a managed entity instance belonging to the * current persistence context. * * @param entity * @return boolean indicating if entity is in persistence context * @throws IllegalArgumentException * if not an entity * @see javax.persistence.EntityManager#contains(java.lang.Object) */ @Override public final boolean contains(Object entity) { checkClosed(); return getPersistenceDelegator().contains(entity); }
/** * Refresh the state of the instance from the database, overwriting changes * made to the entity, if any. */ public void refresh(Object entity) { if (contains(entity)) { MainCache mainCache = (MainCache) getPersistenceCache().getMainCache(); Node node = mainCache.getNodeFromCache(entity, getMetadata(entity.getClass()), this); // Locking as it might read from persistence context. try { lock.readLock().lock(); node.setPersistenceDelegator(this); node.refresh(); } finally { lock.readLock().unlock(); } } else { throw new IllegalArgumentException("This is not a valid or managed entity, can't be refreshed"); } }
@Test public void testContains() { PersonnelDTO dto = new PersonnelDTO(); dto.setPersonId("123"); PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator(); Assert.assertFalse(pd.contains(dto)); em.persist(dto); pd = ((EntityManagerImpl) em).getPersistenceDelegator(); Assert.assertTrue(pd.contains(dto)); em.clear(); pd = ((EntityManagerImpl) em).getPersistenceDelegator(); Assert.assertFalse(pd.contains(dto)); }
@Test public void testDetach() { PersonnelDTO dto = new PersonnelDTO(); PersistenceDelegator pd = ((EntityManagerImpl) em).getPersistenceDelegator(); try { pd.detach(dto); } catch (IllegalArgumentException e) { Assert.assertEquals("Primary key not set into entity", e.getMessage()); } dto.setPersonId("123"); try { pd.detach(dto); } catch (IllegalArgumentException e) { Assert.fail(); } Assert.assertFalse(pd.contains(dto)); em.persist(dto); pd.detach(dto); Assert.assertFalse(pd.contains(dto)); }