public void revoke(Set<DataverseRole> roles, RoleAssignee assignee, DvObject defPoint) { for (DataverseRole role : roles) { em.createNamedQuery("RoleAssignment.deleteByAssigneeIdentifier_RoleIdDefinition_PointId") .setParameter("assigneeIdentifier", assignee.getIdentifier()) .setParameter("roleId", role.getId()) .setParameter("definitionPointId", defPoint.getId()) .executeUpdate(); em.refresh(role); } em.refresh(assignee); }
@Test public void checkPositionsNotNull() throws Exception { EntityManager em = getEm(); HIterationProject project = em.find(HIterationProject.class, 1l); // assertThat( project, notNullValue() ); HDocument hdoc = new HDocument("fullpath", ContentType.TextPlain, en_US); hdoc.setProjectIteration(project.getProjectIterations().get(0)); List<HTextFlow> textFlows = hdoc.getTextFlows(); HTextFlow flow1 = new HTextFlow(hdoc, "textflow1", "some content"); HTextFlow flow2 = new HTextFlow(hdoc, "textflow2", "more content"); textFlows.add(flow1); textFlows.add(flow2); em.persist(hdoc); em.flush(); // em.clear(); // hdoc = em.find(HDocument.class, docId); em.refresh(hdoc); List<HTextFlow> textFlows2 = hdoc.getTextFlows(); assertThat(textFlows2.size(), is(2)); flow1 = textFlows2.get(0); assertThat(flow1, notNullValue()); flow2 = textFlows2.get(1); assertThat(flow2, notNullValue()); // TODO: we should automate this... hdoc.incrementRevision(); textFlows2.remove(flow1); flow1.setObsolete(true); dao.syncRevisions(hdoc, flow1); // flow1.setPos(null); em.flush(); em.refresh(hdoc); em.refresh(flow1); em.refresh(flow2); assertThat(hdoc.getTextFlows().size(), is(1)); flow2 = hdoc.getTextFlows().get(0); assertThat(flow2.getResId(), equalTo("textflow2")); flow1 = hdoc.getAllTextFlows().get("textflow1"); // assertThat(flow1.getPos(), nullValue()); assertThat(flow1.isObsolete(), is(true)); assertThat(flow1.getRevision(), is(2)); flow2 = hdoc.getAllTextFlows().get("textflow2"); // assertThat(flow1.getPos(), is(0)); assertThat(flow2.isObsolete(), is(false)); }
@Transactional @RequestMapping(value = "/fileRegistered", method = RequestMethod.POST) public ModelAndView newFileRegistered( @ModelAttribute("file") file file, BindingResult result1, @ModelAttribute("client") @Valid client client, BindingResult result2, ModelAndView model) { if (result1.hasErrors()) { model.setViewName("error"); System.out.println("File error"); return model; } if (result2.hasErrors()) { model.setViewName("error"); System.out.println("Client error"); return model; } model.setViewName("success"); em.persist(client); em.flush(); em.refresh(client); file.setClient_ClientID(client.getClientId()); em.persist(file); mapFileWithEmployee(file.getFileNumber(), file.getFileName(), file.getAssignedAdvocate()); return model; }
@Transactional public AccessKey authenticate(@NotNull String key) { Optional<AccessKey> accessKeyOpt = genericDAO .createNamedQuery(AccessKey.class, "AccessKey.getByKey", Optional.of(CacheConfig.get())) .setParameter("someKey", key) .getResultList() .stream() .findFirst(); if (!accessKeyOpt.isPresent()) { return null; } AccessKey accessKey = accessKeyOpt.get(); final Long expirationPeriod = configurationService.getLong(Constants.SESSION_TIMEOUT, Constants.DEFAULT_SESSION_TIMEOUT); if (accessKey.getExpirationDate() != null) { final Long expiresIn = accessKey.getExpirationDate().getTime() - timestampService.getTimestamp().getTime(); if (AccessKeyType.SESSION == accessKey.getType() && expiresIn > 0 && expiresIn < expirationPeriod / 2) { em.refresh(accessKey, LockModeType.PESSIMISTIC_WRITE); accessKey.setExpirationDate( new Date(timestampService.getTimestamp().getTime() + expirationPeriod)); return genericDAO.merge(accessKey); } } return accessKey; }
public void refresh(Map map) { try { entityManager.refresh(map); } catch (RuntimeException e) { throw e; } }
/** * Refresh method test loads an entity with two different entity managers. One updates the entity * and another refreshes it. The test checks whether refreshed entity contains changes. */ @Test public void entityEquality_refresh_EntityManager() { // load an entity EntityManager emRefresh = factory.createEntityManager(); Person person1 = emRefresh.find(Person.class, SIMON_SLASH_ID); // load the same entity by different entity manager EntityManager emChange = factory.createEntityManager(); Person person2 = emChange.find(Person.class, SIMON_SLASH_ID); // change the first entity - second entity remains the same emRefresh.getTransaction().begin(); person1.setFirstName("refreshDemo"); assertNotSame("refreshDemo", person2.getFirstName()); // commit the transaction - second entity still remains the same emRefresh.getTransaction().commit(); assertNotSame("refreshDemo", person2.getFirstName()); // refresh second entity - it changes emChange.refresh(person2); assertEquals("refreshDemo", person2.getFirstName()); emRefresh.close(); emChange.close(); }
public void refresh(Base base) { try { entityManager.refresh(base); } catch (RuntimeException e) { throw e; } }
/** * Finds a Person in the database given its id. * * @param personId The id of the person * @return The found person */ public static Person getPersonById(int personId) { EntityManager em = Assignment3Dao.instance.createEntityManager(); Person person = em.find(Person.class, personId); if (person != null) em.refresh(person); Assignment3Dao.instance.closeConnections(em); return person; }
/** Test refresh. */ public void testRefresh() { EntityManager em = createEntityManager(); beginTransaction(em); Order order = new Order(); try { order.id = this.nextId++; order.orderedBy = "ACME"; order.address = new Address(); order.address.city = "Ottawa"; em.persist(order); commitTransaction(em); } finally { closeEntityManagerAndTransaction(em); } clearCache(); em = createEntityManager(); beginTransaction(em); try { order = em.find(Order.class, order.id); order.orderedBy = "Fred Jones"; em.refresh(order); if (order.orderedBy.equals("Fred Jones")) { fail("Refresh failed: " + order.orderedBy); } } finally { closeEntityManagerAndTransaction(em); } }
public void testPostPersistBusInheritAndDefault() { int busListenerPostPersistCountBefore = BusListener.POST_PERSIST_COUNT; int fueledVehiclePostPersistCountBefore = FueledVehicleListener.POST_PERSIST_COUNT; int defaultListenerPostPersistCountBefore = DefaultListener.POST_PERSIST_COUNT; int defaultListenerPostLoadCountBefore = DefaultListener.POST_LOAD_COUNT; int defaultListenerPostLoadCountIntermidiate; EntityManager em = createEntityManager(); beginTransaction(em); try { Bus bus = new Bus(); bus.setPassengerCapacity(new Integer(50)); bus.setFuelCapacity(new Integer(175)); bus.setDescription("OC Transpo Bus"); bus.setFuelType("Diesel"); em.persist(bus); em.flush(); // This should fire a postLoad event ... em.refresh(bus); defaultListenerPostLoadCountIntermidiate = DefaultListener.POST_LOAD_COUNT; javax.persistence.Query q = em.createQuery("select distinct b from Bus b where b.id = " + bus.getId()); // This should not fire a postLoad event ... q.getResultList(); commitTransaction(em); } catch (RuntimeException ex) { if (isTransactionActive(em)) { rollbackTransaction(em); } closeEntityManager(em); throw ex; } int busListenerPostPersistCountAfter = BusListener.POST_PERSIST_COUNT; int fueledVehiclePostPersistCountAfter = FueledVehicleListener.POST_PERSIST_COUNT; int defaultListenerPostPersistCountAfter = DefaultListener.POST_PERSIST_COUNT; int defaultListenerPostLoadCountAfter = DefaultListener.POST_LOAD_COUNT; assertFalse( "The PostPersist callback method on BusListener was not called.", busListenerPostPersistCountBefore == busListenerPostPersistCountAfter); assertFalse( "The PostPersist callback method on FueledVehicleListener was not called.", fueledVehiclePostPersistCountBefore == fueledVehiclePostPersistCountAfter); assertFalse( "The PostPersist callback method on DefaultListener was not called.", defaultListenerPostPersistCountBefore == defaultListenerPostPersistCountAfter); assertTrue( "The PostLoad callback method on DefaultListener was called more than once, possibly on the refresh.", (defaultListenerPostLoadCountIntermidiate - defaultListenerPostLoadCountBefore) == 1); assertTrue( "The PostLoad callback method on DefaultListener was called on the getQueryResult().", defaultListenerPostLoadCountIntermidiate == defaultListenerPostLoadCountAfter); }
public Usuario refresh(Usuario usuario) { entityManager.getTransaction().begin(); Usuario u = entityManager.merge(usuario); entityManager.refresh(u); entityManager.getTransaction().commit(); entityManager.close(); return u; }
@Override public void setPrintReadState(EntityPrint.EnumReadStatus readState, EntityPrint print) { print = em.merge(print); em.refresh(print); print.setReadStatus(readState); em.persist(print); em.flush(); }
@Override protected Product createMock() { com.tasktop.c2c.server.internal.tasks.domain.Product mockProduct = MockProductFactory.create(entityManager); entityManager.flush(); entityManager.refresh(mockProduct); return (Product) mockProduct; }
@Override public CulturalCategory createCulturalCategory(CulturalCategory culturalCategory) throws Exception { em.persist(culturalCategory); em.flush(); em.refresh(culturalCategory); return culturalCategory; }
public void reload() { TypedQuery<Article> q = em.createQuery("select u from Article u", Article.class); articles = q.getResultList(); for (Article a : articles) { em.refresh(a); } fireTableDataChanged(); }
@Override public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) { EntityManager em = getCurrent(); if (em != null) { em.refresh(entity, lockMode, properties); return; } em = createEntityManager(); try { em.refresh(entity, lockMode, properties); } finally { freeEntityManager(em); } }
/** * Find person by id * * @param personId * @return */ public static Person getPersonById(int personId) { EntityManager em = LifeStyleDao.instance.createEntityManager(); Person p = em.find(Person.class, personId); if (p != null) em.refresh(p); LifeStyleDao.instance.closeConnections(em); return p; }
@Override @Transactional(value = "transactionManager") public T refresh(final PK id) { if (type == null) { throw new UnsupportedOperationException("The type must be set to use this method."); } T managedEntity = entityManager.find(type, id); entityManager.refresh(managedEntity); return managedEntity; }
@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; }
protected Object saveOrUpdate(final Object entity) { Object updatedEntity = entity; try { if (!entityManager.contains(entity)) { updatedEntity = entityManager.merge(entity); } } catch (IllegalArgumentException e) { // Exception thrown from merge method because entity does not yet exist in the DB entityManager.persist(updatedEntity); } entityManager.flush(); entityManager.refresh(updatedEntity); return updatedEntity; }
public VDC findByAlias(String alias) { String query = "SELECT v from VDC v where v.alias = :fieldName"; VDC vdc = null; try { vdc = (VDC) em.createQuery(query).setParameter("fieldName", alias).getSingleResult(); em.refresh( vdc); // Refresh because the cached object doesn't include harvestingDataverse object - // need to review why this is happening } catch (javax.persistence.NoResultException e) { // Do nothing, just return null. } return vdc; }
/** Refresh on detached entity throws an IllegalArgumentException. */ @Test public void refreshDetachedEntity() { EntityManager em = factory.createEntityManager(); Person person1 = em.find(Person.class, SIMON_SLASH_ID); em.detach(person1); try { em.refresh(person1); } catch (IllegalArgumentException ex) { em.close(); return; } fail("An exception was expected."); }
/** Refresh the state of the instance from the database. */ @Override public void refresh(Object entity) { EntityManager em = getCurrent(); if (em != null) { em.refresh(entity); return; } try { if (_ut.getStatus() == Status.STATUS_NO_TRANSACTION) throw new TransactionRequiredException(L.l("refresh must be called within transaction.")); } catch (SystemException e) { throw new RuntimeException(e); } em = createEntityManager(); try { em.refresh(entity); } finally { freeEntityManager(em); } }
@GET @Path("/list/{userId}") @Produces("application/json") public Response getJsonList(@PathParam("userId") int id) { User user = em.find(User.class, id); if (user != null) { em.refresh(user); List<Account> list = user.getAccounts(); if (!list.isEmpty()) { GenericEntity<List<Account>> entity = new GenericEntity<List<Account>>(list) {}; return Response.ok(entity).build(); } } return Response.status(Status.NOT_FOUND).build(); }
@Override @Transactional public ProfileImpl getById(String userId) throws NotFoundException, ServerException { requireNonNull(userId, "Required non-null id"); try { final EntityManager manager = managerProvider.get(); final ProfileImpl profile = manager.find(ProfileImpl.class, userId); if (profile == null) { throw new NotFoundException(format("Couldn't find profile for user with id '%s'", userId)); } manager.refresh(profile); return profile; } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }
// email, password // notificationType, notficationId, @POST @Path("getall") @Consumes("application/json") @Produces("application/json") public JsonObject putJson(JsonObject content) { String email = content.getString(JsonStrings.email); String password = content.getString(JsonStrings.password); JsonObjectBuilder builder = Json.createObjectBuilder(); User user = null; try { user = em.createNamedQuery("User.findByEmail", User.class) .setParameter("email", email) .getSingleResult(); } catch (NoResultException e) { } if (user == null) { throw new UnsupportedOperationException(); } if (!user.getPassword().equals(password)) { throw new UnsupportedOperationException(); } activeBean.register(content, user); em.refresh(em.merge(user)); Collection<UsersNotifications> usersNotifications = null; usersNotifications = user.getUsersNotificationsCollection(); if (usersNotifications == null || usersNotifications.isEmpty()) { builder.add(JsonStrings.newNotifications, false); return builder.build(); } builder.add(JsonStrings.newNotifications, true); JsonArrayBuilder arrayBuilder = Json.createArrayBuilder(); for (UsersNotifications notification : usersNotifications) { JsonObjectBuilder internalBuilder = Json.createObjectBuilder(); internalBuilder.add(JsonStrings.notificationType, notification.getNotificationType()); internalBuilder.add(JsonStrings.notificationItemId, notification.getNotifyId()); arrayBuilder.add(internalBuilder); } em.createNamedQuery("UsersNotifications.deleteByUserId") .setParameter("userId", user) .executeUpdate(); em.flush(); builder.add(JsonStrings.notificationTable, arrayBuilder); return builder.build(); }
public static void main(String... args) { EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("JpaBasicsTutorial"); EntityManager em = emFactory.createEntityManager(); EntityManager em1 = emFactory.createEntityManager(); Person person = new Person(); em.getTransaction().begin(); person.setName("Merry Jane"); System.out.println("Before peprsist: " + person); em.persist(person); System.out.println("After peprsist: " + person); em.flush(); System.out.println("After flush: " + person); em.getTransaction().commit(); System.out.println("After commit: " + person); em.getTransaction().begin(); person = em.find(Person.class, person.getId(), LockModeType.WRITE); System.out.println("Founded person: " + person); em.getTransaction().commit(); System.out.println("After commit: " + person); em.getTransaction().begin(); person = em.find(Person.class, person.getId(), LockModeType.OPTIMISTIC_FORCE_INCREMENT); System.out.println("Founded person: " + person); em.flush(); System.out.println("Founded person after flush: " + person); em.getTransaction().rollback(); System.out.println("After rollback: " + person); // Case does not works em1.getTransaction().begin(); Person person1 = em.find(Person.class, person.getId(), LockModeType.NONE); person.setName("John"); em.getTransaction().begin(); person = em.find(Person.class, person.getId(), LockModeType.WRITE); System.out.println("Founded person: " + person); em1.getTransaction().rollback(); em.refresh(person); em.flush(); System.out.println("Founded person after flush: " + person); em.getTransaction().commit(); System.out.println("After flush and commit: " + person); }
@Override public void addBook(EntityBook book, EntityRelease release, EntityAuthor author) { // Autor se umisti do databaze. if (author.getId() != null) { author = em.merge(author); em.refresh(author); } else { em.persist(author); } // Propoji se autor s knihou. book.getAuthorCollection().add(author); author.getBookCollection().add(book); em.persist(book); em.persist(author); // Vytvori se nove vydani knihy. release.setBook(book); book.getReleasesCollection().add(release); em.persist(book); em.persist(release); // Ziska se uzivatel. Principal principal = sessionContext.getCallerPrincipal(); EntityUser user = beanSessionUser.getUserByEmail(principal.getName()); // Vytvori se novy vytisk knihy. EntityPrint print = new EntityPrint(); print.setRelease(release); release.getPrintsCollection().add(print); print.setOwnershipType(EntityPrint.EnumOwnershipType.PHYSICAL); print.setReadStatus(EntityPrint.EnumReadStatus.UNREAD); print.setUser(user); user.getPrintsCollection().add(print); em.persist(print); em.persist(release); em.persist(user); em.flush(); }
private void validateCycleFree(Task task, Errors errors) { Queue<Task> queue = new LinkedList<Task>(); for (Dependency dep : task.getDependenciesesForBlocked()) { queue.add(dep.getBugsByDependson()); } while (!queue.isEmpty()) { Task node = entityManager.find(Task.class, queue.remove().getId()); if (node.getId().equals(task.getId())) { errors.reject("task.dependency.cycle"); return; } entityManager.refresh(node); for (Dependency dep : node.getDependenciesesForBlocked()) { queue.add(dep.getBugsByDependson()); } } }
// Note: Update all for Table Per class only works with the one single // reference class. So it's not a full feature test. public void testUpdateAllQuery() { EntityManager em = createEntityManager(); beginTransaction(em); try { ExpressionBuilder eb = new ExpressionBuilder(); UpdateAllQuery updateQuery = new UpdateAllQuery(Assassin.class); updateQuery.addUpdate(eb.get("name"), "Generic Assassin Name"); ((JpaEntityManager) em.getDelegate()).getServerSession().executeQuery(updateQuery); Assassin assassin = (Assassin) em.find(ContractedPersonel.class, assassinId); em.refresh(assassin); commitTransaction(em); assertTrue("Update all did not work", assassin.getName().equals("Generic Assassin Name")); } catch (Exception e) { e.printStackTrace(); fail("Error issuing update all contracted personel query: " + e.getMessage()); } finally { if (isTransactionActive(em)) { rollbackTransaction(em); } closeEntityManager(em); } }