List of usage examples for javax.persistence EntityManager createQuery
public Query createQuery(CriteriaDelete deleteQuery);
Query
for executing a criteria delete query. From source file:corner.orm.gae.impl.PaginatedJapEntityService.java
License:asdf
/** * * magic paginate method.//w ww .ja va 2s . c om * eg: * <code> * options.setPage(2); * * * paginate(Member.class,new Object[]{"email=?","asdf@asdf.net"},"userName desc",options) * paginate(Member.class,"email='asdf@asdf.net'","userName desc",options) * * List conditions = new ArrayList(); * conditions.add("userName=? and password=?"); * conditions.add(userName); * conditions.add(password); * paginate(Member.class,conditions,"userName desc",options) * * </code> * Magic conditions query criteria * @param persistClass persistence class * @param conditions query criteria * @param order order by sql * @param options pagination options. * @return include result and totalRecord. */ public PaginationList paginate(final Class<?> persistClass, final Object conditions, final String order, final PaginationOptions options) { final Iterable con = typeCoercer.coerce(conditions, Iterable.class); return (PaginationList) this.template.execute(new JpaCallback() { @Override public Object doInJpa(EntityManager entityManager) throws PersistenceException { final Iterator it = con == null ? null : con.iterator(); String conditionJPQL = buildConditionJPQL(persistClass, it).toString(); //query list final StringBuffer queryJPQL = new StringBuffer(conditionJPQL); appendOrder(queryJPQL, order); queryJPQL.insert(0, "select root." + EntityConstants.ID_PROPERTY_NAME); Query query = entityManager.createQuery(queryJPQL.toString()); //count query final StringBuffer countJPQL = new StringBuffer(conditionJPQL); countJPQL.insert(0, "select count(root) "); Query countQuery = entityManager.createQuery(countJPQL.toString()); if (it != null) { int i = 0; while (it.hasNext()) { i++; Object obj = it.next(); query.setParameter(String.valueOf(i), obj); countQuery.setParameter(String.valueOf(i), obj); } } //get perpage int perPage = options.getPerPage(); int page = options.getPage(); if (page < 1) { page = 1; } query.setFirstResult((page - 1) * perPage); query.setMaxResults(perPage); PaginationList list = new PaginationList(query.getResultList().iterator(), options); //query total record number //beacause jpa rowCount is integer type.so convert as long options.setTotalRecord(Long.parseLong(countQuery.getSingleResult().toString())); return list; } }); }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.test.CommandITCase.java
/** * Test delete.// www .jav a 2 s . c o m * * @throws Exception the exception */ @Test public void testDelete() throws Exception { long size = countArticles(); EntityManager em = emf.createEntityManager(); String[] ids = new String[] { "132" }; // insert all items for (String id : ids) { // item should not be in the db Query query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(0, query.getResultList().size()); // load content String content = getContent("src/test/resources/inbox/add/pressreleasesdetails_" + id + ".xml", "hibernate"); // send content to jms broker template.sendBody("jms:topic:BUS_OUT", content); // wait Thread.sleep(TimeOuts.LONG); query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(1, query.getResultList().size()); } // wait Thread.sleep(TimeOuts.LONG); assertEquals("not all items are present", size + ids.length, countArticles()); // now send the delete command for (String id : ids) { // load content String content = getContent("src/test/resources/inbox/delete/pressreleasesdetails_" + id + ".xml", "hibernate"); // send content to jms broker template.sendBody("jms:topic:BUS_OUT", content); // wait Thread.sleep(TimeOuts.LONG); // item should be deleted Query query = em.createQuery( new StringBuilder().append("SELECT x FROM news x WHERE x.fs_id = ").append(id).toString()); assertEquals(0, query.getResultList().size()); } assertEquals("ups, there are items left in the db", size, countArticles()); em.close(); }
From source file:de.iai.ilcd.model.dao.ProcessDao.java
@SuppressWarnings("unchecked") public List<GeographicalArea> getAllLocations() { EntityManager em = PersistenceUtil.getEntityManager(); return em.createQuery("select distinct area from GeographicalArea area order by area.name").getResultList(); }
From source file:de.iai.ilcd.model.dao.ProcessDao.java
@SuppressWarnings("unchecked") public List<GeographicalArea> getUsedLocations() { EntityManager em = PersistenceUtil.getEntityManager(); return em.createQuery( "select distinct area from Process p, GeographicalArea area where p.geography.location=area.areaCode order by area.name") .getResultList();/* ww w . ja v a2 s. c o m*/ }
From source file:de.iai.ilcd.model.dao.ProcessDao.java
@SuppressWarnings("unchecked") public List<Integer> getReferenceYears() { EntityManager em = PersistenceUtil.getEntityManager(); return em.createQuery( "select distinct p.timeInformation.referenceYear from Process p order by p.timeInformation.referenceYear asc") .getResultList();//w w w.j a v a 2s . c o m }
From source file:com.easyjf.core.dao.impl.GenericDAOImpl.java
public T getBy(final String propertyName, final Object value) { if (propertyName == null || "".equals(propertyName) || value == null) throw new IllegalArgumentException(I18n.getLocaleMessage( "ext.Call.parameter.is.not.correct.attribute.names.and.values.are.not.empty")); List<T> ret = (List<T>) this.getJpaTemplate().execute(new JpaCallback() { public Object doInJpa(EntityManager em) throws PersistenceException { String clazzName = clazz.getName(); StringBuffer sb = new StringBuffer("select obj from "); sb.append(clazzName).append(" obj"); Query query = null;/* w w w. j a v a 2s .c o m*/ if (propertyName != null && value != null) { sb.append(" where obj.").append(propertyName).append(" = :value"); query = em.createQuery(sb.toString()).setParameter("value", value); } else { query = em.createQuery(sb.toString()); } return query.getResultList(); } }); if (ret != null && ret.size() == 1) { return ret.get(0); } else if (ret != null && ret.size() > 1) { throw new java.lang.IllegalStateException("worning --more than one object find!!"); } else { return null; } }
From source file:net.echinopsii.ariane.community.plugin.rabbitmq.directory.RabbitmqDirectoryBootstrap.java
private void plugDirectoryJPAProvider() { Company pivotal = null;/*w ww .j a v a 2 s. c om*/ Application rabbitmq = null; directoryJpaProvider.addSubPersistenceBundle(FrameworkUtil.getBundle(RabbitmqDirectoryBootstrap.class)); EntityManager em = directoryJpaProvider.createEM(); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Company> cmpCriteria = builder.createQuery(Company.class); Root<Company> cmpRoot = cmpCriteria.from(Company.class); cmpCriteria.select(cmpRoot).where(builder.equal(cmpRoot.<String>get("name"), "Pivotal")); TypedQuery<Company> cmpQuery = em.createQuery(cmpCriteria); try { pivotal = cmpQuery.getSingleResult(); log.debug("Pivotal company already defined ..."); } catch (NoResultException e) { log.debug("Pivotal company will be defined ..."); } catch (Exception e) { throw e; } CriteriaQuery<Application> appCriteria = builder.createQuery(Application.class); Root<Application> appRoot = appCriteria.from(Application.class); appCriteria.select(appRoot).where(builder.equal(appRoot.<String>get("name"), "RabbitMQ")); TypedQuery<Application> appQuery = em.createQuery(appCriteria); try { rabbitmq = appQuery.getSingleResult(); log.debug("RabbitMQ application already defined ..."); } catch (NoResultException e) { log.debug("RabbitMQ application will be defined ..."); } catch (Exception e) { throw e; } em.getTransaction().begin(); if (pivotal == null) { pivotal = new Company().setNameR("Pivotal").setDescriptionR("Pivotal"); em.persist(pivotal); } if (rabbitmq == null) { rabbitmq = new Application().setNameR("RabbitMQ").setCompanyR(pivotal).setShortNameR("RabbitMQ") .setColorCodeR("ff6600").setDescriptionR("Robust messaging for applications"); em.persist(rabbitmq); } if (!pivotal.getApplications().contains(rabbitmq)) { pivotal.getApplications().add(rabbitmq); } em.flush(); em.getTransaction().commit(); }
From source file:org.grails.datastore.mapping.jpa.query.JpaQuery.java
Object executeQuery(final PersistentEntity entity, final Junction criteria, EntityManager em, boolean singleResult) { JpaQueryBuilder queryBuilder = new JpaQueryBuilder(entity, criteria, projections, orderBy); queryBuilder.setConversionService(session.getDatastore().getMappingContext().getConversionService()); JpaQueryInfo jpaQueryInfo = queryBuilder.buildSelect(); List parameters = jpaQueryInfo.getParameters(); final String queryToString = jpaQueryInfo.getQuery(); if (LOG.isDebugEnabled()) { LOG.debug("Built JPQL to execute: " + queryToString); }/* www . ja v a 2 s. c om*/ final javax.persistence.Query q = em.createQuery(queryToString); if (parameters != null) { for (int i = 0, count = parameters.size(); i < count; i++) { q.setParameter(i + 1, parameters.get(i)); } } q.setFirstResult(offset); if (max > -1) { q.setMaxResults(max); } if (!singleResult) { return q.getResultList(); } return q.getSingleResult(); }
From source file:org.ow2.proactive.scheduling.api.graphql.fetchers.DatabaseConnectionFetcher.java
@VisibleForTesting int getNbEntriesBeforeSlicing(EntityManager entityManager, Class<E> entityClass, CriteriaBuilder criteriaBuilder, Predicate[] predicates) { CriteriaQuery<Long> counterQuery = criteriaBuilder.createQuery(Long.class); CriteriaQuery<Long> select = counterQuery.select(criteriaBuilder.count(counterQuery.from(entityClass))); if (predicates.length > 0) { select.where(predicates);//from w ww.j a v a 2 s . com } return entityManager.createQuery(counterQuery).getSingleResult().intValue(); }
From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java
public ActionMessages validate(CustomAttributeGroupMaintActionForm form, String siteId) throws Exception { ActionMessages errors = new ActionMessages(); boolean insertMode = false; if (form.getMode().equals("C")) { insertMode = true;//w w w .jav a 2 s .com } if (Format.isNullOrEmpty(form.getCustomAttribGroupName())) { errors.add("customAttribName", new ActionMessage("error.string.required")); } EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); String sql = "from CustomAttributeGroup " + "where siteId = :siteId " + "and customAttribGroupName = :customAttribGroupName "; if (!insertMode) { sql += "and customAttribGroupId != :customAttribGroupId"; } Query query = em.createQuery(sql); query.setParameter("siteId", siteId); query.setParameter("customAttribGroupName", form.getCustomAttribGroupName()); if (!insertMode) { query.setParameter("customAttribGroupId", Long.valueOf(form.getCustomAttribGroupId())); } if (query.getResultList().size() > 0) { errors.add("customAttribGroupName", new ActionMessage("error.customAttributeGroup.exist")); } return errors; }