List of usage examples for javax.persistence.criteria CriteriaBuilder parameter
<T> ParameterExpression<T> parameter(Class<T> paramClass, String name);
From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * subquery(equivalent to dowhere1) : exists * SELECT e FROM jpa_query_employee e WHERE EXISTS (SELECT p FROM e.projects p WHERE p.name = :projectname) *//*from w w w .j av a 2 s . c o m*/ @Transactional public void doWhere2() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> c = cb.createQuery(Employee.class); Root<Employee> e = c.from(Employee.class); // subquery Subquery<Project> sq = c.subquery(Project.class); // Root<Project> p = sq.from(Project.class); Root<Employee> se = sq.correlate(e); Join<Employee, Project> p = se.join("projects"); sq.select(p).where(cb.equal(p.get("name"), cb.parameter(String.class, "projectname"))); // c.select(e).where(cb.exists(sq)); }
From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java
/** * @since 5.0//from w w w .java 2 s .c o m * @param marketplaceRatingPK the primary key of the entity you want * @return Set of ratings per portlet definition */ @PortalTransactionalReadOnly @OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME) public Set<IMarketplaceRating> getRatingsByFname(String fname) { //Build criteria to fetch MarketplaceRatingImpl based on the incoming portlet name. final EntityManager entityManager = this.getEntityManager(); final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<IMarketplaceRating> getByPortlet = cb.createQuery(IMarketplaceRating.class); final Root<MarketplaceRatingImpl> imr = getByPortlet.from(MarketplaceRatingImpl.class); getByPortlet.select(imr); //Define the path to the portlet fName final Path<MarketplaceRatingPK> mrPK = imr.get("marketplaceRatingPK"); final Path<PortletDefinitionImpl> mrIPD = mrPK.get("portletDefinition"); final ParameterExpression<String> portletFName = cb.parameter(String.class, "portletFName"); getByPortlet.where(cb.equal(mrIPD.get("fname"), portletFName)); TypedQuery<IMarketplaceRating> tq = entityManager.createQuery(getByPortlet); tq.setParameter("portletFName", fname); List<IMarketplaceRating> resultList = tq.getResultList(); Set<IMarketplaceRating> resultSet = new HashSet<IMarketplaceRating>(resultList); return resultSet; }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}//from ww w.j av a2s.c om */ //@SuppressWarnings("unchecked") public List<VolumeInsert> findVolumeInserts(Integer volNum, String volLetExt) { CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); CriteriaQuery<VolumeInsert> cq = criteriaBuilder.createQuery(VolumeInsert.class); Root<Image> root = cq.from(Image.class); cq.select(criteriaBuilder.construct(VolumeInsert.class, root.get("volNum"), root.get("volLetExt"), root.get("insertNum"), root.get("insertLet"))).distinct(true); cq.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt")) : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText), criteriaBuilder.isNotNull(root.get("insertNum")))); cq.orderBy(criteriaBuilder.asc(root.get("insertNum")), criteriaBuilder.asc(root.get("insertLet"))); /* The above query is equivalent to the following: * SELECT DISTINCT volNum, volLetExt, insertNum, insertLet FROM Image * WHERE * volNum = :volNum * AND volLetExt (<nullable> ? 'IS NULL' : ':volLetExt') * AND insertNum IS NOT NULL * ORDER BY * insertNum ASC, * insertLet ASC */ TypedQuery<VolumeInsert> tq = getEntityManager().createQuery(cq); tq.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) tq.setParameter("volLetExt", volLetExt); return tq.getResultList(); }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}//from ww w .ja v a 2 s. c o m */ @Override public List<Image> findImages(Integer volNum, String volLetExt) throws PersistenceException { // Create criteria objects CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class); Root<Image> root = criteriaQuery.from(Image.class); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt")) : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText))); // Set values in predicate's elements TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery); typedQuery.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { typedQuery.setParameter("volLetExt", volLetExt); } return typedQuery.getResultList(); }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * This method updates every totals in input. * /* ww w .j a v a2s . co m*/ * @param explorer input object to be update. */ @SuppressWarnings({ "unchecked", "rawtypes" }) private <T extends VolumeExplorer> void updateExplorerTotals(T explorer) { CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class); Root<Image> rootCount = criteriaQueryCount.from(Image.class); criteriaQueryCount.select(criteriaBuilder.count(rootCount)); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQueryCount .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum), StringUtils.isEmpty(explorer.getVolLetExt()) ? criteriaBuilder.isNull(rootCount.get("volLetExt")) : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText))); TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount); typedQueryCount.setParameter("volNum", explorer.getVolNum()); if (!StringUtils.isEmpty(explorer.getVolLetExt())) typedQueryCount.setParameter("volLetExt", explorer.getVolLetExt()); explorer.setTotal((Long) typedQueryCount.getSingleResult()); StringBuilder stringBuilder = new StringBuilder( "SELECT imageType, imageRectoVerso, max(imageProgTypeNum) FROM Image WHERE volNum=:volNum and volLetExt "); if (!StringUtils.isEmpty(explorer.getVolLetExt())) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" is null"); stringBuilder.append(" group by imageType, imageRectoVerso"); Query query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", explorer.getVolNum()); if (!StringUtils.isEmpty(explorer.getVolLetExt())) { query.setParameter("volLetExt", explorer.getVolLetExt()); } List<Object[]> result = (List<Object[]>) query.getResultList(); // We init every partial-total explorer.setTotalRubricario(new Long(0)); explorer.setTotalCarta(new Long(0)); explorer.setTotalAppendix(new Long(0)); explorer.setTotalOther(new Long(0)); explorer.setTotalGuardia(new Long(0)); // We set new partial-total values for (int i = 0; i < result.size(); i++) { // This is an array defined as [ImageType, Count by ImageType] Object[] singleGroup = result.get(i); if (((ImageType) singleGroup[0]).equals(ImageType.R)) { if (explorer.getTotalRubricario() < new Long(singleGroup[2].toString())) { explorer.setTotalRubricario(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.C)) { if (explorer.getTotalCarta() < new Long(singleGroup[2].toString())) { explorer.setTotalCarta(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.A)) { if (explorer.getTotalAppendix() < new Long(singleGroup[2].toString())) { explorer.setTotalAppendix(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.O)) { if (explorer.getTotalOther() < new Long(singleGroup[2].toString())) { explorer.setTotalOther(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.G)) { if (explorer.getTotalGuardia() < new Long(singleGroup[2].toString())) { explorer.setTotalGuardia(new Long(singleGroup[2].toString())); } } } }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}/*from www . java2 s . co m*/ */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public FoliosInformations findVolumeFoliosInformations(Integer volNum, String volLetExt) throws PersistenceException { FoliosInformations foliosInformations = new FoliosInformations(); CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class); Root<Image> rootCount = criteriaQueryCount.from(Image.class); criteriaQueryCount.select(criteriaBuilder.count(rootCount)); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQueryCount .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt")) : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText))); TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount); typedQueryCount.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) typedQueryCount.setParameter("volLetExt", volLetExt); foliosInformations.setTotal((Long) typedQueryCount.getSingleResult()); StringBuilder stringBuilder = new StringBuilder( "SELECT imageType, imageRectoVerso, max(imageProgTypeNum) FROM Image WHERE volNum=:volNum and volLetExt "); if (!StringUtils.isEmpty(volLetExt)) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" is null"); stringBuilder.append(" GROUP BY imageType, imageRectoVerso"); Query query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { query.setParameter("volLetExt", volLetExt); } List<Object[]> result = (List<Object[]>) query.getResultList(); // We init every partial-total foliosInformations.setTotalRubricario(new Long(0)); foliosInformations.setTotalCarta(new Long(0)); foliosInformations.setTotalAppendix(new Long(0)); foliosInformations.setTotalOther(new Long(0)); foliosInformations.setTotalGuardia(new Long(0)); foliosInformations.setTotalMissingFolios(0); // We set new partial-total values for (int i = 0; i < result.size(); i++) { // This is an array defined as [ImageType, Count by ImageType] Object[] singleGroup = result.get(i); if (((ImageType) singleGroup[0]).equals(ImageType.R)) { if (foliosInformations.getTotalRubricario() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalRubricario(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.C)) { if (foliosInformations.getTotalCarta() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalCarta(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.A)) { if (foliosInformations.getTotalAppendix() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalAppendix(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.O)) { if (foliosInformations.getTotalOther() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalOther(new Long(singleGroup[2].toString())); } } else if (((ImageType) singleGroup[0]).equals(ImageType.G)) { if (foliosInformations.getTotalGuardia() < new Long(singleGroup[2].toString())) { foliosInformations.setTotalGuardia(new Long(singleGroup[2].toString())); } } } // Calculating missing folios start stringBuilder = new StringBuilder( "SELECT DISTINCT(imageProgTypeNum) FROM Image WHERE volNum = :volNum AND volLetExt "); if (!StringUtils.isEmpty(volLetExt)) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" IS NULL"); stringBuilder.append(" AND imageType = 'C'"); // we search only for folios stringBuilder.append(" ORDER BY imageProgTypeNum ASC"); query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { query.setParameter("volLetExt", volLetExt); } List<Integer> foliosOnVolume = (List<Integer>) query.getResultList(); for (long i = 1; i <= foliosInformations.getTotalCarta(); i++) { for (int j = 0; j < foliosOnVolume.size(); j++) { if (foliosOnVolume.get(j) == i) { break; } else if (foliosOnVolume.get(j) > i) { foliosInformations.setTotalMissingFolios(foliosInformations.getTotalMissingFolios() + 1); //LP : Missing numbering is first counter!!!! foliosInformations.getMissingNumberingFolios().add(((Long) i).intValue()); break; } } } // Calculating missing folios end //Extracting misnumbered Folios... stringBuilder = new StringBuilder( "SELECT concat(imageProgTypeNum, missedNumbering) FROM Image WHERE volNum=:volNum and volLetExt "); if (!StringUtils.isEmpty(volLetExt)) stringBuilder.append(" = :volLetExt"); else stringBuilder.append(" is null"); stringBuilder.append(" and missedNumbering is not null ORDER BY imageProgTypeNum ASC"); query = getEntityManager().createQuery(stringBuilder.toString()); query.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { query.setParameter("volLetExt", volLetExt); } foliosInformations.setMisnumberedFolios((List<String>) query.getResultList()); return foliosInformations; }
From source file:org.medici.bia.dao.image.ImageDAOJpaImpl.java
/** * {@inheritDoc}/*w w w.j av a2 s . c o m*/ */ @SuppressWarnings("rawtypes") @Override public Page findImages(Integer volNum, String volLetExt, PaginationFilter paginationFilter) throws PersistenceException { // Create criteria objects CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder(); Page page = new Page(paginationFilter); if (paginationFilter.getTotal() == null) { CriteriaQuery<Long> criteriaQueryCount = criteriaBuilder.createQuery(Long.class); Root<Image> rootCount = criteriaQueryCount.from(Image.class); criteriaQueryCount.select(criteriaBuilder.count(rootCount)); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); criteriaQueryCount .where(criteriaBuilder.and(criteriaBuilder.equal(rootCount.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(rootCount.get("volLetExt")) : criteriaBuilder.equal(rootCount.get("volLetExt"), parameterVolLeText))); TypedQuery typedQueryCount = getEntityManager().createQuery(criteriaQueryCount); typedQueryCount.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { typedQueryCount.setParameter("volLetExt", volLetExt); } page.setTotal(new Long((Long) typedQueryCount.getSingleResult())); } CriteriaQuery<Image> criteriaQuery = criteriaBuilder.createQuery(Image.class); Root<Image> root = criteriaQuery.from(Image.class); // Define predicate's elements ParameterExpression<Integer> parameterVolNum = criteriaBuilder.parameter(Integer.class, "volNum"); ParameterExpression<String> parameterVolLeText = StringUtils.isEmpty("volLetExt") ? null : criteriaBuilder.parameter(String.class, "volLetExt"); //We need to duplicate predicates beacause they are link to Root element criteriaQuery.where(criteriaBuilder.and(criteriaBuilder.equal(root.get("volNum"), parameterVolNum), StringUtils.isEmpty(volLetExt) ? criteriaBuilder.isNull(root.get("volLetExt")) : criteriaBuilder.equal(root.get("volLetExt"), parameterVolLeText))); // Set values in predicate's elements TypedQuery<Image> typedQuery = getEntityManager().createQuery(criteriaQuery); typedQuery.setParameter("volNum", volNum); if (!StringUtils.isEmpty(volLetExt)) { typedQuery.setParameter("volLetExt", volLetExt); } //Pagination will work with index [1 ... total] and not [0 ... total1-] typedQuery.setFirstResult(paginationFilter.getFirstRecord() - 1); typedQuery.setMaxResults(paginationFilter.getLength()); page.setList(typedQuery.getResultList()); return page; }
From source file:gov.osti.services.Metadata.java
/** * Acquire a List of records in pending ("Submitted") state, to be approved * for indexing and searching./*from w w w .j a va 2 s.c o m*/ * * JSON response is of the form: * * {"records":[{"code_id":n, ...} ], * "start":0, "rows":20, "total":100} * * Where records is an array of DOECodeMetadata JSON, start is the beginning * row number, rows is the number requested (or total if less available), * and total is the total number of rows matching the filter. * * Return Codes: * 200 - OK, JSON is returned as above * 401 - Unauthorized, login is required * 403 - Forbidden, insufficient privileges (role required) * 500 - unexpected error * * @param start the starting row number (from 0) * @param rows number of rows desired (0 is unlimited) * @param siteCode (optional) a SITE OWNERSHIP CODE to filter by site * @param state the WORKFLOW STATE if desired (default Submitted and Announced). One of * Approved, Saved, Submitted, or Announced, if supplied. * @return JSON of a records response */ @GET @Path("/projects/pending") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RequiresAuthentication @RequiresRoles("OSTI") public Response listProjectsPending(@QueryParam("start") int start, @QueryParam("rows") int rows, @QueryParam("site") String siteCode, @QueryParam("state") String state) { EntityManager em = DoeServletContextListener.createEntityManager(); try { // get a JPA CriteriaBuilder instance CriteriaBuilder cb = em.getCriteriaBuilder(); // create a CriteriaQuery for the COUNT CriteriaQuery<Long> countQuery = cb.createQuery(Long.class); Root<DOECodeMetadata> md = countQuery.from(DOECodeMetadata.class); countQuery.select(cb.count(md)); Expression<String> workflowStatus = md.get("workflowStatus"); Expression<String> siteOwnershipCode = md.get("siteOwnershipCode"); // default requested STATE; take Submitted and Announced as the default values if not supplied List<DOECodeMetadata.Status> requestedStates = new ArrayList(); String queryState = (StringUtils.isEmpty(state)) ? "" : state.toLowerCase(); switch (queryState) { case "approved": requestedStates.add(DOECodeMetadata.Status.Approved); break; case "saved": requestedStates.add(DOECodeMetadata.Status.Saved); break; case "submitted": requestedStates.add(DOECodeMetadata.Status.Submitted); break; case "announced": requestedStates.add(DOECodeMetadata.Status.Announced); break; default: requestedStates.add(DOECodeMetadata.Status.Submitted); requestedStates.add(DOECodeMetadata.Status.Announced); break; } Predicate statusPredicate = workflowStatus.in(requestedStates); ParameterExpression<String> site = cb.parameter(String.class, "site"); if (null == siteCode) { countQuery.where(statusPredicate); } else { countQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site))); } // query for the COUNT TypedQuery<Long> cq = em.createQuery(countQuery); cq.setParameter("status", requestedStates); if (null != siteCode) cq.setParameter("site", siteCode); long rowCount = cq.getSingleResult(); // rows count should be less than 100 for pagination; 0 is a special case rows = (rows > 100) ? 100 : rows; // create a CriteriaQuery for the ROWS CriteriaQuery<DOECodeMetadata> rowQuery = cb.createQuery(DOECodeMetadata.class); rowQuery.select(md); if (null == siteCode) { rowQuery.where(statusPredicate); } else { rowQuery.where(cb.and(statusPredicate, cb.equal(siteOwnershipCode, site))); } TypedQuery<DOECodeMetadata> rq = em.createQuery(rowQuery); rq.setParameter("status", requestedStates); if (null != siteCode) rq.setParameter("site", siteCode); rq.setFirstResult(start); if (0 != rows) rq.setMaxResults(rows); RecordsList records = new RecordsList(rq.getResultList()); records.setTotal(rowCount); records.setStart(start); return Response.ok().entity(mapper.valueToTree(records).toString()).build(); } finally { em.close(); } }