List of usage examples for javax.persistence EntityManager createQuery
public Query createQuery(CriteriaDelete deleteQuery);
Query
for executing a criteria delete query. From source file:net.officefloor.tutorial.transactionhttpserver.TransactionHttpServerTest.java
/** * Requests the page, creates a user and fails to create a user. */// ww w.j av a 2s . c o m // START SNIPPET: test public void testCreateUser() throws Exception { // Request page this.doRequest("http://localhost:7878/users.woof"); // Create user with all details this.doRequest("http://localhost:7878/users-create.woof?username=melanie&fullname=Melanie+Sagenschneider"); // Attempt to create user that will fail database constraints this.doRequest("http://localhost:7878/users-create.woof?username=joe"); // Validate melanie added EntityManager manager = Persistence.createEntityManagerFactory("example").createEntityManager(); User melanie = (User) manager.createQuery("SELECT U FROM User U WHERE U.userName = 'melanie'") .getSingleResult(); assertEquals("Melanie created", "Melanie Sagenschneider", melanie.getPerson().getFullName()); // Validate joe not added try { manager.createQuery("SELECT U FROM User U WHERE U.userName = 'joe'").getSingleResult(); fail("Should not find Joe"); } catch (NoResultException ex) { } }
From source file:com.webbfontaine.valuewebb.timer.RatesUpdater.java
@Asynchronous @Transactional//from w w w. j a v a 2 s. c o m public QuartzTriggerHandle scheduleTask(@Expiration Date when, @IntervalCron String interval) { HashMap<String, BigDecimal> ratesFromBank = ratesFromBank(); if (ratesFromBank.isEmpty()) { LOGGER.error("No rates passed to update, check web site and source code!"); return null; } EntityManager entityManager = Utils.getEntityManager(); List<Rate> existingRates = entityManager.createQuery("from Rate r where r.eov is null").getResultList(); Transaction tx = ((org.jboss.seam.persistence.HibernateSessionProxy) entityManager.getDelegate()) .getTransaction(); try { tx.begin(); for (Rate existingRecord : existingRates) { BigDecimal latestRateForCurrency = ratesFromBank.get(existingRecord.getCod()); if (latestRateForCurrency == null) { LOGGER.warn("Currency code '{0}' exists but absent in updates", existingRecord.getCod()); continue; } if (existingRecord.getExch().doubleValue() != latestRateForCurrency.doubleValue()) { //i get double value because bigdecimal can return 0.2240 which is not equal to 0.224 when comparing BD values /* close existing rate and open new one from today */ Date tomorrowDate = Utils.getTomorrowDate(); existingRecord.setEov(tomorrowDate); // since scheduler works at 21:00 Rate newRecord = new Rate(null, existingRecord.getCod(), 1, latestRateForCurrency, tomorrowDate, null); entityManager.persist(existingRecord); entityManager.persist(newRecord); LOGGER.info("Updated Exchange rate for {0}, old: {1}, new: {2}", newRecord.getCod(), existingRecord.unitRate(), newRecord.unitRate()); } } entityManager.flush(); tx.commit(); } catch (Exception e) { LOGGER.error("Exception on updating rates", e); if (tx != null) { tx.rollback(); } } return null; }
From source file:com.github.jrh3k5.membership.renewal.mailer.service.jpa.JpaMembershipService.java
@SuppressWarnings("unchecked") @Override/*w ww . j a v a 2 s . com*/ public Collection<JpaMembershipRecord> getLapsedMemberships(Date lowerExclusiveBound, Date upperInclusiveBound) { LOGGER.info("Finding members who have lapsed memberships between ({}, {}]", lowerExclusiveBound, upperInclusiveBound); final EntityManager entityManager = entityManagerFactory.createEntityManager(); try { final Query query = entityManager.createQuery( "select m from MembershipRecord m where m.latestMembershipDate > :lowerBound and m.latestMembershipDate <= :upperBound"); query.setParameter("lowerBound", lowerExclusiveBound); query.setParameter("upperBound", upperInclusiveBound); return query.getResultList(); } finally { entityManager.close(); } }
From source file:net.officefloor.tutorial.transactionhttpserver.TransactionHttpServerTest.java
/** * Ensure the JPA connects to database./* w ww . j a v a 2 s. co m*/ */ public void testJpa() throws Exception { // Request page to allow time for database setup this.doRequest("http://localhost:7878/users.woof"); // Obtain entity manager EntityManagerFactory factory = Persistence.createEntityManagerFactory("example"); EntityManager manager = factory.createEntityManager(); // Ensure can obtain user and person Query query = manager.createQuery("SELECT U FROM User U"); User user = (User) query.getSingleResult(); assertEquals("Incorrect user name", "daniel", user.getUserName()); Person person = user.getPerson(); assertEquals("Incorrect person name", "Daniel Sagenschneider", person.getFullName()); // Ensure persist user and person User newUser = new User(); newUser.setUserName("test"); Person newPerson = new Person(); newPerson.setFullName("TEST"); newPerson.setUser(newUser); manager.persist(newPerson); manager.close(); // Ensure user and person persisted manager = factory.createEntityManager(); User retrievedUser = manager.find(User.class, newUser.getId()); assertEquals("Incorrect retrieved user name", "test", retrievedUser.getUserName()); Person retrievedPerson = retrievedUser.getPerson(); assertEquals("Incorrect retrieved full name", "TEST", retrievedPerson.getFullName()); // Close persistence factory.close(); }
From source file:de.egore911.opengate.services.GameserverService.java
@GET @Path("/purge") @Produces("text/plain") @Documentation("Internal method to remove the gameservers that haven't been seen for more than one hour.") public Response purgeGameservers() { EntityManager em = EntityManagerFilter.getEntityManager(); Calendar oneHourAgo = Calendar.getInstance(); oneHourAgo.add(Calendar.MINUTE, -15); int deleted = em.createQuery("delete from Gameserver gameserver where lastSeen > :lastSeen") .setParameter("lastSeen", oneHourAgo.getTime()).executeUpdate(); return Response.ok(Integer.toString(deleted)).build(); }
From source file:com.ewcms.publication.PublishIntegratedTest.java
private void updateArticleStutas() { JpaTemplate template = createJpaTemplate(); template.execute(new JpaCallback<Object>() { @Override// w w w .ja v a 2s.c om public Object doInJpa(EntityManager em) throws PersistenceException { em.getTransaction().begin(); String hql = "Update Article o Set o.status=?1 Where o.status = ?2"; Query query = em.createQuery(hql); query.setParameter(1, Article.Status.PRERELEASE); query.setParameter(2, Article.Status.RELEASE); query.executeUpdate(); em.getTransaction().commit(); return null; } }); }
From source file:com.ewcms.publication.PublishIntegratedTest.java
private void updateResourceStutas() { JpaTemplate template = createJpaTemplate(); template.execute(new JpaCallback<Object>() { @Override/* w w w . j a v a 2s .c o m*/ public Object doInJpa(EntityManager em) throws PersistenceException { em.getTransaction().begin(); String hql = "Update Resource o Set o.status= ?1 Where o.status = ?2"; Query query = em.createQuery(hql); query.setParameter(1, Resource.Status.NORMAL); query.setParameter(2, Resource.Status.RELEASED); query.executeUpdate(); em.getTransaction().commit(); return null; } }); }
From source file:de.iai.ilcd.model.dao.CommonDataStockDao.java
/** * Get all readable data stocks/*from w ww . ja va2 s . com*/ * * @param lstSar * list of stock access rights * @return list of all readable data stocks */ @SuppressWarnings("unchecked") private List<AbstractDataStock> getAllReadable(List<StockAccessRight> lstSar) { List<Long> readableStockIds = new ArrayList<Long>(); for (StockAccessRight sar : lstSar) { if (ProtectionType.READ.isContained(sar.getValue())) { readableStockIds.add(sar.getStockId()); } } if (readableStockIds.isEmpty()) { return Collections.emptyList(); } EntityManager em = PersistenceUtil.getEntityManager(); return em.createQuery("select a from " + this.getJpaName() + " a WHERE a.id IN(" + StringUtils.join(readableStockIds, ",") + ")").getResultList(); }
From source file:com.ewcms.publication.PublishIntegratedTest.java
private void updateTemplateSourceStutas() { JpaTemplate template = createJpaTemplate(); template.execute(new JpaCallback<Object>() { @Override//from ww w .j a v a 2 s . com public Object doInJpa(EntityManager em) throws PersistenceException { em.getTransaction().begin(); String hql = "Update TemplateSource o Set o.release= ?1 Where o.release = ?2"; Query query = em.createQuery(hql); query.setParameter(1, Boolean.FALSE); query.setParameter(2, Boolean.TRUE); query.executeUpdate(); em.getTransaction().commit(); return null; } }); }
From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java
/** * Template, reduce this code using spring dao support? * //from www. ja v a2 s . c o m * EntityManager em = emf.createEntityManager(); try{ EntityTransaction tx = em.getTransaction(); tx.begin(); * tx.commit(); }finally{ em.close(); } */ private User getUserByName(EntityManager em, String userName) { Query q = em.createQuery("select u from User u where u.name = '" + userName + "'"); List<?> resultList = q.getResultList(); return resultList.size() == 0 ? null : (User) resultList.get(0); }