List of usage examples for javax.persistence EntityManager createQuery
public Query createQuery(CriteriaDelete deleteQuery);
Query
for executing a criteria delete query. From source file:eu.forgestore.ws.impl.FStoreJpaController.java
public List<Course> readCoursesMetadataByOwnerId(int userid, int firstResult, int maxResults) { EntityManager entityManager = entityManagerFactory.createEntityManager(); Query q;// w w w . j av a 2s . c om q = entityManager.createQuery("SELECT a FROM Course a WHERE a.owner.id=" + userid + " ORDER BY a.id"); q.setFirstResult(firstResult); q.setMaxResults(maxResults); return q.getResultList(); }
From source file:eu.forgestore.ws.impl.FStoreJpaController.java
public List<FIREAdapter> readFIREAdaptersMetadataByOwnerId(int userid, int firstResult, int maxResults) { EntityManager entityManager = entityManagerFactory.createEntityManager(); Query q;//from ww w.j av a 2 s . co m q = entityManager.createQuery("SELECT a FROM FIREAdapter a WHERE a.owner.id=" + userid + " ORDER BY a.id"); q.setFirstResult(firstResult); q.setMaxResults(maxResults); return q.getResultList(); }
From source file:eu.forgestore.ws.impl.FStoreJpaController.java
public void getAllCategoriesPrinted() { logger.info("================= getAllCategoriesPrinted() ==================START"); EntityManager entityManager = entityManagerFactory.createEntityManager(); List<Category> lb = entityManager.createQuery("select p from Category p").getResultList(); for (Iterator iterator = lb.iterator(); iterator.hasNext();) { Category sm = (Category) iterator.next(); logger.info(" ======> Category found: " + sm.getName() + ", Id: " + sm.getId()); }//from w w w .ja v a2s. c o m }
From source file:com.sixsq.slipstream.persistence.Run.java
public static int viewListCount(User user, String moduleResourceUri, String cloudServiceName) throws ConfigurationException, ValidationException { int count = 0; EntityManager em = PersistenceUtil.createEntityManager(); try {/*w w w . ja va 2 s .c o m*/ CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Long> critQuery = builder.createQuery(Long.class); Root<Run> rootQuery = critQuery.from(Run.class); critQuery.select(builder.count(rootQuery)); Predicate where = viewListCommonQueryOptions(builder, rootQuery, user, moduleResourceUri, cloudServiceName); if (where != null) { critQuery.where(where); } TypedQuery<Long> query = em.createQuery(critQuery); count = (int) (long) query.getSingleResult(); } finally { em.close(); } return count; }
From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java
/** * Deletes a news article from the db//from w w w . j a v a2 s . c o m * * @param entity The article to delete */ public void delete(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // Query query = em.createQuery(new StringBuilder().append("SELECT x FROM Article x WHERE x.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString()); Query query = em.createQuery(new StringBuilder() .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString()); query.setParameter("fsid", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { Article art = (Article) query.getSingleResult(); em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); throw e; } logger.error("Failure while deleting from the database", e); } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:eu.forgestore.ws.impl.FStoreJpaController.java
public void getAllUsersPrinted() { logger.info("================= getAllUsers() ==================START"); EntityManager entityManager = entityManagerFactory.createEntityManager(); List<FStoreUser> lb = entityManager.createQuery("select p from FStoreUser p").getResultList(); for (Iterator iterator = lb.iterator(); iterator.hasNext();) { FStoreUser bu = (FStoreUser) iterator.next(); logger.info(" ======> FStoreUser found: " + bu.getName() + ", Id: " + bu.getId() + ", Id: " + bu.getOrganization() + ", username: " + bu.getUsername()); List<Product> products = bu.getProducts(); for (Product prod : products) { logger.info(" ======> bunMetadata found: " + prod.getName() + ", Id: " + prod.getId() + ", getUuid: " + prod.getUuid() + ", getName: " + prod.getName()); }/*from w ww . ja va 2 s . c om*/ } logger.info("================= getAll() ==================END"); }
From source file:BO.UserHandler.java
public boolean updateDeviceToken(VUser u) { EntityManager em; EntityManagerFactory emf;// w w w . j av a 2 s .co m emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); System.out.println("Updating token: " + u.getDeviceToken()); try { em.getTransaction().begin(); User user; user = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email") .setParameter("email", u.getEmail()).setMaxResults(1).getSingleResult(); user.setDeviceToken(u.getDeviceToken()); em.persist(user); em.flush(); em.getTransaction().commit(); return true; } catch (NoResultException e) { return false; } finally { if (em != null) { em.close(); } emf.close(); } }
From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.PersistentDocumentStoreController.java
/** * Gets all UUIDs for {@code T} type document stores owned by the given owner. * @param em the {@link EntityManager} to use. * @param ownerId the ID of the owner./*from w ww . j a v a 2s . com*/ * @param entityClass the specific type of document stores to be retrieved; must be annotated with the {@link Entity} annotation. * @return a {@link List} containing {@link String} representations of the UUIDs. */ public <T extends PersistentDocumentStore> List<String> getAllUuids(EntityManager em, String ownerId, Class<T> entityClass) { Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em"); Validate.notNull(ownerId, CannedMessages.NULL_ARGUMENT, "ownerId"); Validate.notNull(entityClass, CannedMessages.NULL_ARGUMENT, "entityClass"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<byte[]> cq = cb.createQuery(byte[].class); Root<T> store = cq.from(entityClass); cq.multiselect(store.get("id")) .where(cb.equal(store.get("ownerId"), cb.parameter(String.class, "ownerId"))); TypedQuery<byte[]> tq = em.createQuery(cq); tq.setParameter("ownerId", ownerId); return Lists.newArrayList(Iterables.transform(tq.getResultList(), UuidUtils.uuidBytesToStringFunction())); }
From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.CommandITCase.java
/** * Test cleanup./* w w w .jav a 2 s . c om*/ * * @throws Exception the exception */ @Test public void testCleanup() throws Exception { assertEquals("DB not empty", 0, countArticles()); EntityManager em = emf.createEntityManager(); String[] ids = new String[] { "128", "130", "131", "132", "256", "704" }; int numberOfArticles = ids.length; // insert all items for (String id : ids) { // item should not be in the db Query query = em.createQuery( new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString()); assertEquals(0, query.getResultList().size()); // load content String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml", "hibernate"); // patch content - add createTime content = content.replace("<uxb_entity ", "<uxb_entity createTime=\"" + System.currentTimeMillis() + "\" "); // send content to jms broker template.sendBody("jms:topic:BUS_OUT", content); } // wait Thread.sleep(TimeOuts.LONG); assertEquals("not all items are present", numberOfArticles, countArticles()); // Save the current time as expiredate long expiredate = System.currentTimeMillis(); ids = new String[] { "128", "130", "131" }; int numberOfNewArticles = ids.length; // insert new items for (String id : ids) { // item should be in the db Query query = em.createQuery( new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString()); assertEquals(1, query.getResultList().size()); // load content String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml", "hibernate"); // patch content - add createTime content = content.replace("<uxb_entity ", "<uxb_entity createTime=\"" + System.currentTimeMillis() + "\" "); // send content to jms broker template.sendBody("jms:topic:BUS_OUT", content); } // wait Thread.sleep(TimeOuts.LONG); assertEquals("not all items are present", numberOfArticles, countArticles()); // now check, that old items are cleaned up for (String id : ids) { // load content String content = getContent("src/test/resources/inbox/cleanup/pressreleasesdetails.xml", "hibernate"); // patch content - add createTime content = content.replace("<uxb_entity ", "<uxb_entity createTime=\"" + expiredate + "\" "); // send content to jms broker template.sendBody("jms:topic:BUS_OUT", content); } // wait Thread.sleep(TimeOuts.LONG); // Check number of articles assertEquals("ups, there are too many items left in the db", numberOfNewArticles, countArticles()); // Check article ids for (String id : ids) { // item should be in the db Query query = em.createQuery( new StringBuilder().append("SELECT x FROM article x WHERE x.aid = ").append(id).toString()); assertEquals(1, query.getResultList().size()); } em.close(); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * gets the metaCategory for its fs_id.//from www . j a va2 s .c om * * @param fs_id The fs_id * @param language the language * @param em the em * @return the NewsCategory instance */ private NewsMetaCategory getNewsMetaCategory(Long fs_id, String language, EntityManager em) { Query categoryQuery = em.createQuery(new StringBuilder() .append("SELECT x FROM metaCategory x WHERE x.fs_id = :fs_id AND x.language = :language") .toString()); // or fsidindex2? categoryQuery.setParameter("fs_id", fs_id); categoryQuery.setParameter("language", language); if (categoryQuery.getResultList().size() > 0) { return (NewsMetaCategory) categoryQuery.getSingleResult(); } return null; }