@Test public void testPersistence() { try { em.getTransaction().begin(); Student u = new Student(); u.setScore(12); u.setName("eskatos"); em.persist(u); assertTrue(em.contains(u)); em.remove(u); assertFalse(em.contains(u)); em.getTransaction().commit(); } catch (Exception ex) { em.getTransaction().rollback(); ex.printStackTrace(); fail("Exception during testPersistence"); } }
@Test public void testPersistCascading() { Map<String, String> aMap = new HashMap<String, String>(); aMap.put(ConfigKeys.FACTORY, MutableTestDataSourceFactory.class.getName()); aMap.put("files", TestJPA.DATA_FILE); EntityManager aManager = Empire.get() .persistenceProvider() .createEntityManagerFactory("test", aMap) .createEntityManager(); // ================= test persist cascade LaunchUsingProxy aNewLaunchWithProxy = new LaunchUsingProxy(); Launch aNewLaunch = new Launch(); Spacecraft aNewOtherSpacecraft = new Spacecraft(); aNewOtherSpacecraft.setRdfId( new SupportsRdfId.URIKey( URI.create("http://empire.clarkparsia.com/test/persist/cascade/aNewOtherSpacecraft"))); aNewOtherSpacecraft.setAgency("agency"); aNewLaunchWithProxy.setOtherSpacecraft(aNewOtherSpacecraft); aNewLaunch.setOtherSpacecraft(aNewOtherSpacecraft); aManager.persist(aNewLaunch); assertTrue(aManager.contains(aNewLaunch)); // it was persisted as a relation... assertTrue( aManager .find(Launch.class, aNewLaunch.getRdfId()) .getOtherSpacecraft() .getRdfId() .equals(aNewOtherSpacecraft.getRdfId())); // but persist does not cascade assertFalse(aManager.contains(aNewOtherSpacecraft)); aManager.persist(aNewLaunchWithProxy); assertTrue(aManager.contains(aNewLaunchWithProxy)); // it was persisted as a relation... assertTrue( aManager .find(LaunchUsingProxy.class, aNewLaunchWithProxy.getRdfId()) .getOtherSpacecraft() .equals(aNewOtherSpacecraft)); // and this should be true now because the persist was cascaded assertTrue(aManager.contains(aNewOtherSpacecraft)); }
public void testCascadePersist() throws Exception { EntityManager em = getEntityManagerAndClearStorageBackend(); CascadeFrom from = new CascadeFrom(); from.setAll(new CascadeTo()); from.setPersist(new CascadeTo()); em.persist(from); em.flush(); assertTrue(em.contains(from)); assertTrue(em.contains(from.getAll())); assertTrue(em.contains(from.getPersist())); }
public Boolean updateUserWithoutSession(String SID, Long USER_ID) { try { log.debug("updateUser User: "******" || " + SID); TypedQuery<Sessiondata> query = em.createNamedQuery("getSessionById", Sessiondata.class); query.setParameter("session_id", SID); List<Sessiondata> sessions = query.getResultList(); Sessiondata sessiondata = null; if (sessions != null && sessions.size() > 0) { sessiondata = sessions.get(0); } if (sessiondata == null) { log.error("Could not find session to Update"); return false; } log.debug("Found session to update: " + sessiondata.getSession_id() + " userId: " + USER_ID); sessiondata.setRefresh_time(new Date()); sessiondata.setUser_id(USER_ID); if (sessiondata.getId() == null) { em.persist(sessiondata); } else { if (!em.contains(sessiondata)) { em.merge(sessiondata); } } return true; } catch (Exception ex2) { log.error("[updateUser]: ", ex2); } return null; }
// @TransactionAttribute(TransactionAttributeType.REQUIRED) @Override public ContentItem saveContentItem(@Update ContentItem item) { // TODO: this should rather be solved declaratively by an appropriate modification of @RDF item.getResource().setLabel(null, item.getTitle()); item.setModified(new Date()); // TODO: this method should raise an event to invalidate all caches that are // currently holding an instance of this content item if (item.getId() == null) { log.debug("Persisting new ContentItem #0 ", item); kiwiEntityManager.persist(item); } else if (!entityManager.contains(item)) { log.info("Merging ContentItem #0 ", item.getId()); item = entityManager.merge(item); } else { log.debug("Do nothing with ContentItem #0 ", item.getId()); } // if there is multimedia data in this content item, extract it... if (item.getMediaContent() != null) { MultimediaService ms = (MultimediaService) Component.getInstance("multimediaService"); ms.extractMetadata(item); } return item; }
/** * Saves a business object. * * @see * org.kuali.rice.krad.dao.BusinessObjectDao#save(org.kuali.rice.krad.bo.PersistableBusinessObject) */ public PersistableBusinessObject save(PersistableBusinessObject bo) throws DataAccessException { /* KC determined this is not needed for JPA // if collections exist on the BO, create a copy and use to process the // collections to ensure // that removed elements are deleted from the database Set<String> boCollections = getPersistenceStructureService().listCollectionObjectTypes(bo.getClass()).keySet(); PersistableBusinessObject savedBo = null; if (!boCollections.isEmpty()) { // refresh bo to get db copy of collections savedBo = (PersistableBusinessObject) ObjectUtils.deepCopy(bo); for (String boCollection : boCollections) { if (getPersistenceStructureService().isCollectionUpdatable(savedBo.getClass(), boCollection)) { savedBo.refreshReferenceObject(boCollection); } } } */ if (entityManager.contains(bo) && ((HibernateEntityManager) entityManager).getSession().isReadOnly(bo)) { ((HibernateEntityManager) entityManager) .getSession() .setReadOnly(bo, false); // are we read only? turn that off... } return reattachAndSave(bo); }
/** * update the session every time a user makes a request * * @param SID */ private void updatesession(String SID) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Sessiondata> cq = cb.createQuery(Sessiondata.class); Root<Sessiondata> c = cq.from(Sessiondata.class); Predicate condition = cb.equal(c.get("session_id"), SID); cq.where(condition); TypedQuery<Sessiondata> q = em.createQuery(cq); List<Sessiondata> fullList = q.getResultList(); if (fullList.size() == 0) { log.error("Found NO session to updateSession: "); } else { // log.debug("Found session to updateSession: "); Sessiondata sd = fullList.iterator().next(); // log.debug("Found session to updateSession sd "+sd.getUser_id()+" "+sd.getSession_id()); sd.setRefresh_time(new Date()); if (sd.getId() == null) { em.persist(sd); } else { if (!em.contains(sd)) { em.merge(sd); } } } } catch (Exception ex2) { log.error("[updatesession]: ", ex2); } }
public WorkItemInfo merge(WorkItemInfo workItemInfo) { if (this.pessimisticLocking) { if (em.contains(workItemInfo)) { em.lock(workItemInfo, LockModeType.PESSIMISTIC_FORCE_INCREMENT); } else { // Yes, this is a hack, but for detached entities, it's the only way to lock before merging WorkItemInfo dbWorkItemInfo = em.find( WorkItemInfo.class, workItemInfo.getId(), LockModeType.PESSIMISTIC_FORCE_INCREMENT); for (Field field : WorkItemInfo.class.getDeclaredFields()) { boolean access = field.isAccessible(); field.setAccessible(true); try { field.set(dbWorkItemInfo, field.get(workItemInfo)); } catch (Exception e) { logger.error( "Unable to set field " + field.getName() + " of unmerged WorkItemInfo instance!", e); } field.setAccessible(access); } } } return em.merge(workItemInfo); }
public void testDetach() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Tooth tooth = new Tooth(); Mouth mouth = new Mouth(); em.persist(mouth); em.persist(tooth); tooth.mouth = mouth; mouth.teeth = new ArrayList<Tooth>(); mouth.teeth.add(tooth); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); mouth = em.find(Mouth.class, mouth.id); assertNotNull(mouth); assertEquals(1, mouth.teeth.size()); tooth = mouth.teeth.iterator().next(); em.detach(mouth); assertFalse(em.contains(tooth)); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); em.getTransaction().begin(); em.remove(em.find(Mouth.class, mouth.id)); em.getTransaction().commit(); em.close(); }
public Long deleteMeetingMember(Long meetingMemberId) { log.debug("MeetingMemnerDAoImpl.deleteMeetingMember : " + meetingMemberId); try { MeetingMember gm = this.getMeetingMemberById(meetingMemberId); log.debug("ac: " + gm); if (gm == null) { log.debug("Already deleted / Could not find: " + meetingMemberId); return null; } gm.setUpdatetime(new Date()); gm.setDeleted(true); if (gm.getMeetingMemberId() == null) { em.persist(gm); } else { if (!em.contains(gm)) { em.merge(gm); } } return meetingMemberId; } catch (Exception ex2) { log.error("[deleteMeetingMember]: ", ex2); } return null; }
@Override public void delete(StaticAssetStorage assetStorage) { if (!em.contains(assetStorage)) { assetStorage = (StaticAssetStorage) readStaticAssetStorageById(assetStorage.getId()); } em.remove(assetStorage); }
@Test(expectedExceptions = OptimisticLockException.class) public void testOptimisticLockException() { ComponentSpec cs = createComponentSpec( Long.toString(1), "chris", "cs", "type1", "chris", Collections.<Tag>emptyList(), Collections.<String, String>emptyMap()); em.getTransaction().begin(); em.persist(cs); em.getTransaction().commit(); em.clear(); Assert.assertFalse(em.contains(cs)); em.getTransaction().begin(); ComponentSpec orig = em.find(ComponentSpec.class, Long.toString(1)); orig.setComponentName("revisedName"); em.getTransaction().commit(); em.clear(); ComponentSpec current = em.find(ComponentSpec.class, Long.toString(1)); Assert.assertEquals(current.getObjVersion(), 1); Assert.assertEquals(cs.getObjVersion(), 0); em.getTransaction().begin(); em.merge(cs); em.getTransaction() .commit(); // optimistic lock exception should be thrown as there has been an intervening // commit }
@Override public void delete(User user) { LOG.trace(getClass() + " : delete ... "); // em.remove(user); em.remove(em.contains(user) ? user : em.merge(user)); LOG.trace(getClass() + " : delete. "); }
/** Returns true if the entity belongs to the current context. */ @Override public boolean contains(Object entity) { EntityManager em = getCurrent(); if (em != null) { return em.contains(entity); } em = createEntityManager(); try { return em.contains(entity); } finally { freeEntityManager(em); } }
@Override public boolean update(User user) { if (!entityManager.contains(user)) { entityManager.merge(user); } return true; }
public void revoke(RoleAssignment ra) { if (!em.contains(ra)) { ra = em.merge(ra); } em.remove(ra); /** @todo update permissionModificationTime here. */ indexAsync.indexRole(ra); }
/** * Creates a CascadeFrom object, fills in all its related CascadeTo attributes, persists * everything, and flushes the entity manager. Useful as a first step in most tests of cascade * behaviour. * * @param em The entity manager to persist with * @return a newly-created CascadeFrom, persistent and managed by em, with all related CascadeTo * attributes likewise persisted and managed by em. */ private static CascadeFrom createFullyPersistedObject(EntityManager em) { CascadeFrom from = new CascadeFrom(); from.setAll(new CascadeTo()); from.setDetach(new CascadeTo()); from.setMerge(new CascadeTo()); from.setNone(new CascadeTo()); from.setPersist(new CascadeTo()); from.setRefresh(new CascadeTo()); from.setRemove(new CascadeTo()); em.persist(from.getAll()); em.persist(from.getDetach()); em.persist(from.getMerge()); em.persist(from.getNone()); em.persist(from.getPersist()); em.persist(from.getRefresh()); em.persist(from.getRemove()); em.persist(from); em.flush(); assertTrue(em.contains(from)); assertTrue(em.contains(from.getAll())); assertTrue(em.contains(from.getDetach())); assertTrue(em.contains(from.getMerge())); assertTrue(em.contains(from.getNone())); assertTrue(em.contains(from.getPersist())); assertTrue(em.contains(from.getRefresh())); assertTrue(em.contains(from.getRemove())); return from; }
public void testQueryWithManagedPersistentInstanceAsParameter() { EntityManager em = emf.createEntityManager(); Projekt projekt1 = em.find(Projekt.class, ID_PROJEKT1); Projekt projekt2 = em.find(Projekt.class, ID_PROJEKT2); assertTrue(em.contains(projekt1)); assertTrue(em.contains(projekt2)); queryWithParameter(em, projekt1, projekt2); }
public void revoke(RoleAssignment ra) { if (!em.contains(ra)) { ra = em.merge(ra); } em.remove(ra); /** @todo update permissionModificationTime here. */ IndexResponse indexDefinitionPointResult = indexDefinitionPoint(ra.getDefinitionPoint()); logger.fine("indexing operation results: " + indexDefinitionPointResult); }
@Override public StaticAssetStorage save(StaticAssetStorage assetStorage) { if (em.contains(assetStorage)) { return em.merge(assetStorage); } em.persist(assetStorage); em.flush(); return assetStorage; }
@Override @Transactional public void deleteArticle(Long personId, Article news) { User u = entityManager.find(User.class, personId); for (Role r : u.getRole()) { if (Objects.equals(r.getName(), "ADMIN")) { entityManager.remove(entityManager.contains(news) ? news : entityManager.merge(news)); } } }
public Object getPersisted(Object object) { Object id = getId(object); if (id != null) { if (entityManager.contains(object)) { entityManager.detach(object); } return entityManager.find(object.getClass(), id); } return null; }
@Test public void testPositivTx() { final JPAEnvironment env = getEnvironment(); final EntityManager em = env.getEntityManager(); try { env.beginTransaction(em); Employee emp = em.find(Employee.class, new Integer(7)); verify(em.contains(emp), "Object not loaded"); verify(emp.getId() == 7, "wrong id"); verify(emp.getDepartment().getName().equals("eins"), "wrong department"); emp = em.find(Employee.class, new Integer(7)); verify(emp.getId() == 7, "wrong id"); Department dep = em.find(Department.class, new Integer(1)); verify(em.contains(dep), "Object not loaded"); verify(dep.getId() == 1, "wrong id"); env.rollbackTransactionAndClear(em); } finally { closeEntityManager(em); } }
public void remove(BaseEntity instance) { if (em.contains(instance)) { em.remove(instance); } else { BaseEntity persistentInstance = em.find(instance.getClass(), instance.getId()); if (persistentInstance != null) { em.remove(persistentInstance); } } }
public void deleteAdminUser(AdminUser user) { if (!em.contains(user)) { user = em.find( entityConfiguration.lookupEntityClass( "org.broadleafcommerce.openadmin.server.security.domain.AdminUser", AdminUser.class), user.getId()); } em.remove(user); }
public ExternalAccount lookupExternalAccount( Viewpoint viewpoint, User user, ExternalAccountType type) throws NotFoundException { if (!em.contains(user.getAccount())) throw new RuntimeException("detached account in lookupExternalAccount()"); // Right now, external accounts are public, unlike email/aim resources which are friends only... // so we don't need to use the viewpoint. But here in case we want to add it later. ExternalAccount external = user.getAccount().getExternalAccount(type); if (external == null) throw new NotFoundException("No external account of type " + type + " for user " + user); else return external; }
@Override @Transactional(value = "transactionManager") public T refresh(final T transientObject) { T managedEntity = null; if (entityManager.contains(transientObject)) { managedEntity = transientObject; } else { managedEntity = entityManager.merge(transientObject); } entityManager.refresh(managedEntity); return managedEntity; }
@Override public void delete(ServiceType entity) { try { if (em.contains(entity)) { em.remove(entity); } else { em.remove(em.merge(entity)); } } catch (Exception e) { throw new Error(e.getLocalizedMessage()); } }
/** * Remove the 'UserRole' entity * * @param entity 'UserRole' entity that going to remove */ @Transactional public void remove(UserRole entity) { if (entityManager.contains(entity)) { entityManager.remove(entity); } else { System.out.println("UserRole: Remove : Searching for " + entity.toString()); UserRole attached = entityManager.find(UserRole.class, entity.getUsroId()); System.out.println("UserRole: Remove : Found " + attached.toString()); entityManager.remove(attached); } entityManager.flush(); }
@Transactional public void deleteById(long entityId) { // logger.debug("Before Deleting Entity =" + entityId); T entity = findById(entityId); em.remove(em.contains(entity) ? entity : em.merge(entity)); // logger.debug("Before Deleting Entity =" + entityId); }