List of usage examples for javax.persistence.criteria CriteriaQuery from
<X> Root<X> from(Class<X> entityClass);
From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * in and path:/*from w w w . ja v a2 s . c o m*/ * SELECT e FROM jpa_query_employee e WHERE e.address.state IN ('NY','MI') */ @Transactional public void doWhere3() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> c = cb.createQuery(Employee.class); Root<Employee> e = c.from(Employee.class); // method 1 c.select(e).where(e.get("address").get("state").in("NY", "MI")); showResult(c); // method 2 c.select(e).where(cb.in(e.get("address").get("state")).value("NY").value("MI")); showResult(c); }
From source file:org.ow2.proactive.scheduling.api.graphql.fetchers.DatabaseConnectionFetcher.java
/** * Adaptation of the algorithm defined in the GraphQL specification. * <p>// w ww.j a va 2 s .co m * Please look at the following link for more details: * https://facebook.github.io/relay/graphql/connections.htm#sec-Pagination-algorithm * <p> * The opaque cursor that is returned to the client makes use of the entity ID internally. */ protected ExtendedConnection createPaginatedConnection(DataFetchingEnvironment environment, Class<E> entityClass, Function<Root<E>, Path<? extends Number>> entityId, Comparator<E> entityComparator, BiFunction<CriteriaBuilder, Root<E>, List<Predicate[]>> criteria, CursorMapper<T, Integer> cursorMapper) { Integer first = environment.getArgument(FIRST.getName()); Integer last = environment.getArgument(LAST.getName()); Integer after = cursorMapper.getOffsetFromCursor(environment.getArgument(AFTER.getName())); Integer before = cursorMapper.getOffsetFromCursor(environment.getArgument(BEFORE.getName())); CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<E> criteriaQuery = criteriaBuilder.createQuery(entityClass); Root<E> entityRoot = criteriaQuery.from(entityClass); Path<? extends Number> entityIdPath = entityId.apply(entityRoot); Predicate cursorPredicate = createCursorPredicate(criteriaBuilder, entityIdPath, after, before); int maxResults = applySlicing(criteriaQuery, criteriaBuilder, entityIdPath, first, last); CriteriaQuery<E> select = criteriaQuery.select(entityRoot); List<Predicate[]> predicates = criteria.apply(criteriaBuilder, entityRoot); Predicate[] wherePredicate = buildWherePredicate(predicates, cursorPredicate, criteriaBuilder); if (wherePredicate.length > 0) { select.where(wherePredicate); } TypedQuery<E> query = entityManager.createQuery(select); if (maxResults > -1) { query.setMaxResults(maxResults); } Stream<E> dataStream = query.getResultList().stream(); // if last is provided, reverse the stream // in order to get results sorted in ascending order based on entities ID if (last != null) { dataStream = dataStream.sorted(entityComparator); } Stream<T> data = dataMapping(dataStream); ExtendedConnection connection = createRelayConnection(entityManager, entityClass, criteriaBuilder, wherePredicate, cursorMapper, data, first, last); return connection; }
From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * inner join/* ww w. j a v a2 s .co m*/ */ @Transactional public void doFrom1() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Object[]> c = cb.createQuery(Object[].class); Root<Employee> e = c.from(Employee.class); Join<Object, Object> address = e.join("address"); Join<Object, Object> department = e.join("department"); c.multiselect(e, address, department); // .where(cb.and( // cb.equal(address.get("state"), "NY")), // cb.greaterThan(e.<Long>get("salary"), Long.valueOf(1500)), // cb.like(department.<String>get("name"), "department%" // )); showResult(c); }
From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * subquery: in//w ww. j a va2 s . co m * SELECT e FROM jpa_query_employee e WHERE e IN (SELECT emp FROM jpa_query_project p JOIN p.employees pe WHERE p.name = :projectname) */ @Transactional public void doWhere1() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> c = cb.createQuery(Employee.class); Root<Employee> e = c.from(Employee.class); // subquery Subquery<Employee> sq = c.subquery(Employee.class); Root<Project> p = sq.from(Project.class); Join<Project, Employee> pe = p.join("employees"); sq.select(pe).where(cb.equal(p.get("name"), cb.parameter(String.class, "projectname"))); // c.select(e).where(cb.in(e).value(sq)); }
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 ww w . j a v 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:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * SELECT e FROM jpa_query_employee e WHERE e.name= :name *///w ww .jav a 2 s . co m @Transactional public void doParameterQuery() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> c = cb.createQuery(Employee.class); Root<Employee> e = c.from(Employee.class); // parameter, equal to ":name" ParameterExpression<String> paraName = cb.parameter(String.class, "name"); // e.name = ":name" c.select(e).where(cb.equal(e.get("name"), paraName)); // set param value TypedQuery<Employee> query = em.createQuery(c); query.setParameter("name", "employee_1"); List<Employee> result = query.getResultList(); ResultViewer.showResult(result, "criteria query : parameter query"); }
From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * NOTE : Hibernate cannot support case in criteria way * /*from ww w . jav a 2s. c om*/ * case 1: * SELECT p.name, * CASE WHEN TYPE(p)=bq.jpa.demo.query.domain.DesignProject THEN 'dev' * WHEN TYPE(p)=bq.jpa.demo.query.domain.QualityProject THEN 'QA' * ELSE 'unknown' * END * FROM jpa_query_project p * * case 2: * SELECT p.name, * CASE TYPE(p) * WHEN bq.jpa.demo.query.domain.DesignProject THEN 'dev' * WHEN bq.jpa.demo.query.domain.QualityProject THEN 'QA' * ELSE 'unknown' * END * FROM jpa_query_project p */ @Transactional public void doWhere4() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Object[]> c = cb.createQuery(Object[].class); Root<Project> p = c.from(Project.class); // method 1 c.multiselect(p.get("name"), cb.selectCase().when(cb.equal(p.type(), DesignProject.class), "dev") .when(cb.equal(p.type(), QualityProject.class), "QA").otherwise("unknown")); // showResult(c); // method 2: CriteriaQuery<Object[]> c2 = cb.createQuery(Object[].class); Root<Project> p2 = c2.from(Project.class); c2.multiselect(p2.get("name"), cb.selectCase(p2.type()).when(DesignProject.class, "dev") .when(QualityProject.class, "QA").otherwise("unknown")); // showResult(c2); }
From source file:com.netflix.genie.core.jpa.services.JpaJobSearchServiceImpl.java
/** * {@inheritDoc}/*from w ww . java2 s . co m*/ */ @Override public Page<JobSearchResult> findJobs(final String id, final String jobName, final String user, final Set<JobStatus> statuses, final Set<String> tags, final String clusterName, final String clusterId, final String commandName, final String commandId, final Date minStarted, final Date maxStarted, final Date minFinished, final Date maxFinished, @NotNull final Pageable page) { log.debug("called"); final CriteriaBuilder cb = this.entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class); final Root<JobEntity> root = countQuery.from(JobEntity.class); final Predicate whereClause = JpaJobSpecs.getFindPredicate(root, cb, id, jobName, user, statuses, tags, clusterName, clusterId == null ? null : this.clusterRepository.findOne(clusterId), commandName, commandId == null ? null : this.commandRepository.findOne(commandId), minStarted, maxStarted, minFinished, maxFinished); countQuery.select(cb.count(root)).where(whereClause); final Long count = this.entityManager.createQuery(countQuery).getSingleResult(); // Use the count to make sure we even need to make this query if (count > 0) { final CriteriaQuery<JobSearchResult> contentQuery = cb.createQuery(JobSearchResult.class); contentQuery.from(JobEntity.class); contentQuery.multiselect(root.get(JobEntity_.id), root.get(JobEntity_.name), root.get(JobEntity_.user), root.get(JobEntity_.status), root.get(JobEntity_.started), root.get(JobEntity_.finished), root.get(JobEntity_.clusterName), root.get(JobEntity_.commandName)); contentQuery.where(whereClause); final Sort sort = page.getSort(); final List<Order> orders = new ArrayList<>(); sort.iterator().forEachRemaining(order -> { if (order.isAscending()) { orders.add(cb.asc(root.get(order.getProperty()))); } else { orders.add(cb.desc(root.get(order.getProperty()))); } }); contentQuery.orderBy(orders); final List<JobSearchResult> results = this.entityManager.createQuery(contentQuery) .setFirstResult(page.getOffset()).setMaxResults(page.getPageSize()).getResultList(); return new PageImpl<>(results, page, count); } else { return new PageImpl<>(Lists.newArrayList(), page, count); } }
From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java
/** * fetch join://from ww w.j av a2 s . c om * SELECT e FROM jpa_query_employee e JOIN FETCH e.address */ // @Transactional public void doFrom3() { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> c = cb.createQuery(Employee.class); Root<Employee> e = c.from(Employee.class); e.fetch("address"); e.fetch("department"); e.fetch("projects", JoinType.INNER); // e.fetch("phones"); // e.fetch("directs"); // e.fetch("manager"); c.select(e); // only show the fetched data TypedQuery<Employee> query = em.createQuery(c); List<Employee> result = query.getResultList(); for (Employee emp : result) { System.out.println(emp.getId() + " | " + emp.getName() + " | " + emp.getAddress() + " | " + emp.getDepartment() + " | " + emp.getProjects()); } }
From source file:it.attocchi.jpa2.JPAEntityFilter.java
public Predicate getWherePredicate(Class<T> clazz, EntityManagerFactory emf) throws Exception { // CriteriaBuilder CriteriaBuilder criteriaBuilder = emf.getCriteriaBuilder(); CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(clazz); Root<T> root = criteriaQuery.from(clazz); criteriaQuery.select(root);/*from www. j a v a 2 s .c o m*/ List<Predicate> predicateList = new ArrayList<Predicate>(); // return getWherePredicates(emf, predicateList, criteriaQuery, // criteriaBuilder, root); Predicate[] predicates = getWherePredicates(emf, predicateList, criteriaQuery, criteriaBuilder, root); Predicate wherePredicate = criteriaBuilder.and(predicates); return wherePredicate; }