protected <T, T1, T2> PageRequestId<T> findWithSpecification( String requestId, EntityManager entityManager, Pageable pageable, Filter3<T, T1, T2> specification, Class<T> type, Class<T1> type1, Class<T2> type2) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); long total; { CriteriaQuery<Long> cqTotal = builder.createQuery(Long.class); Root<T1> root1 = cqTotal.from(type1); Root<T2> root2 = cqTotal.from(type2); Predicate predicate = specification.toPredicate(root1, root2, cqTotal, builder); if (predicate != null) cqTotal.where(predicate); cqTotal.select(builder.count(root1)); total = entityManager.createQuery(cqTotal).getSingleResult(); } CriteriaQuery<T> cq = builder.createQuery(type); Root<T1> root1 = cq.from(type1); Root<T2> root2 = cq.from(type2); Predicate predicate = specification.toPredicate(root1, root2, cq, builder); if (predicate != null) cq.where(predicate); cq.select(specification.getSelection(root1, root2, cq, builder)); if (pageable.getSort() != null) { List<Order> orders = new LinkedList<Order>(); for (Iterator<org.springframework.data.domain.Sort.Order> itr = pageable.getSort().iterator(); itr.hasNext(); ) { org.springframework.data.domain.Sort.Order order = itr.next(); String sx[] = order.getProperty().split("\\."); Path<Object> p; if (sx[0].equals("t1")) { p = root1.get(sx[1]); } else if (sx[0].equals("t2")) { p = root2.get(sx[1]); } else { throw new RuntimeException("Invalid order " + U.dump(order)); } for (int i = 2, il = sx.length; i < il; i++) p = p.get(sx[i]); if (order.isAscending()) { orders.add(builder.asc(p)); } else { orders.add(builder.desc(p)); } } cq.orderBy(orders); } TypedQuery<T> qry = entityManager.createQuery(cq); qry.setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize()); return new PageRequestIdImpl<T>(qry.getResultList(), pageable, total, requestId); }
public String selectAll(TableDescription table, Pageable page) { Sort sort = page.getSort() != null ? page.getSort() : sortById(table); return format( "SELECT t2__.* FROM ( " + "SELECT row_number() OVER (ORDER BY %s) AS rn__, t1__.* FROM ( %s ) t1__ " + ") t2__ WHERE t2__.rn__ BETWEEN %s AND %s", orderByExpression(sort), selectAll(table), page.getOffset() + 1, page.getOffset() + page.getPageSize()); }
@Override @Transactional(readOnly = true) public Page<UserGroupCheck> findAllByPage(Pageable pageable, Long groupId, long total) { // TODO use setParameter String sql = USER_GROUP_CHECK_QUERY; String orderBy = ""; String sort = ""; Iterator<Order> i = pageable.getSort().iterator(); while (i.hasNext()) { Order order = i.next(); orderBy = order.getProperty(); sort = order.getDirection().name(); } sql = sql.replace(ORDER_BY, orderBy); sql = sql.replace(SORT, sort); Query query = entityManager.createNativeQuery(sql); query.setParameter(GROUP_ID, groupId); query.setParameter(LIMIT, pageable.getPageSize()); query.setParameter(OFFSET, pageable.getOffset()); List<UserGroupCheck> result = JpaUtil.getResultList(query, UserGroupCheck.class); Page<UserGroupCheck> page = new PageImpl<>(result, pageable, total); return page; }
protected <T> PageRequestId<T> findWithSpecification( String requestId, EntityManager entityManager, Pageable pageable, Filter<T> filter, Class<T> type) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); long total; { CriteriaQuery<Long> cqTotal = builder.createQuery(Long.class); Root<T> root = cqTotal.from(type); if (filter != null) { Predicate predicate = filter.toPredicate(root, cqTotal, builder); if (predicate != null) cqTotal.where(predicate); } cqTotal.select(builder.count(root)); total = entityManager.createQuery(cqTotal).getSingleResult(); } CriteriaQuery<T> cq = builder.createQuery(type); Root<T> root = cq.from(type); if (filter != null) { Predicate predicate = filter.toPredicate(root, cq, builder); if (predicate != null) cq.where(predicate); } cq.select(root); if (pageable.getSort() != null) { List<Order> orders = new LinkedList<Order>(); for (Iterator<org.springframework.data.domain.Sort.Order> itr = pageable.getSort().iterator(); itr.hasNext(); ) { org.springframework.data.domain.Sort.Order order = itr.next(); String sx[] = order.getProperty().split("\\."); Path<Object> p = root.get(sx[0]); for (int i = 1, il = sx.length; i < il; i++) p = p.get(sx[i]); if (order.isAscending()) { orders.add(builder.asc(p)); } else { orders.add(builder.desc(p)); } } cq.orderBy(orders); } TypedQuery<T> qry = entityManager.createQuery(cq); qry.setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize()); return new PageRequestIdImpl<T>(qry.getResultList(), pageable, total, requestId); }
protected Map<String, Object> applyPagination(Map<String, Object> parameter, Pageable pageable) { if (pageable == null) return parameter; parameter.put(PAGE_OFFSET, pageable.getOffset()); parameter.put(PAGE_SIZE, pageable.getPageSize()); return applySorting(parameter, pageable.getSort()); }
private Page findBySpecificationAndPredicate( DynamicRepositoryInvoker invoker, final Specification specification, Predicate predicate, final Pageable pageable) { final List<?> items = findItemsBySpecification(invoker, specification, pageable.getSort()); return selectPage(newArrayList(filter(items, predicate)), pageable); }
private String getOrderDesc(final Pageable pageable) { String result = null; Sort sort = pageable.getSort(); if (sort == null) { return result; } final Iterator<Order> iterator = sort.iterator(); while (iterator.hasNext()) { final Order order = iterator.next(); order.getProperty(); } return result; }
@Override public <C, X> Page<C> findAll( Specification<T> spec, Class<C> clazz, Selections<T, C, X> selection, Pageable pageable) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<C> query = builder.createQuery(clazz); Root<T> root = query.from(getDomainClass()); Predicate predicate = spec.toPredicate(root, query, builder); if (predicate != null) { query.where(predicate); } query.select(builder.construct(clazz, selection.select(root, query, builder))); List<Expression<?>> groupBy = query.getGroupList(); Predicate having = query.getGroupRestriction(); if (pageable.getSort() != null) { query.orderBy(toOrders(pageable.getSort(), root, builder)); } TypedQuery<C> typeQuery = em.createQuery(query); return pageable == null ? new PageImpl<>(typeQuery.getResultList()) : readPage(typeQuery, pageable, spec, selection, groupBy, having); }
@Override public <T> Page<T> getPage(Class<T> clazz, Criteria criteria, Pageable pageable) { Criteria countCriteria = HibernateTool.copyCriteria(criteria); long totalItemCount = count(countCriteria); List<T> items = find( clazz, criteria, pageable.getPageNumber() * pageable.getPageSize(), pageable.getPageSize(), CriteriaTool.toOrders(pageable.getSort()).toArray(new Order[0])); return new PageImpl<T>(items, pageable, totalItemCount); }
/** * 分页列表显示数据 为了避免由于权限配置不严格,导致未授权的Controller数据操作访问,父类提供protected基础实现,子类根据需要覆写public然后调用基类方法 * * @return JSON集合数据 */ @MetaData(value = "查询") protected HttpHeaders findByPage() { Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(getRequest()); GroupPropertyFilter groupFilter = GroupPropertyFilter.buildGroupFilterFromHttpRequest(entityClass, getRequest()); String foramt = this.getParameter(PARAM_NAME_FOR_EXPORT_FORMAT); if ("xls".equalsIgnoreCase(foramt)) { exportXlsForGrid(groupFilter, pageable.getSort()); } else { setModel(this.getEntityService().findByPage(groupFilter, pageable)); } return buildDefaultHttpHeaders(); }
@RequiresPermissions("plug:resume:edit") @RequestMapping("edit.do") public String edit( Integer id, Integer position, @PageableDefaults(sort = "id", sortDir = Direction.DESC) Pageable pageable, HttpServletRequest request, org.springframework.ui.Model modelMap) { Integer siteId = Context.getCurrentSiteId(request); Resume bean = service.get(id); Map<String, String[]> params = Servlets.getParameterValuesMap(request, Constants.SEARCH_PREFIX); RowSide<Resume> side = service.findSide(siteId, params, bean, position, pageable.getSort()); modelMap.addAttribute("bean", bean); modelMap.addAttribute("side", side); modelMap.addAttribute("position", position); modelMap.addAttribute(OPRT, EDIT); return "plug/resume/resume_form"; }
@RequestMapping(value = "list", method = RequestMethod.GET) public String listFile( @RequestParam(value = "path", required = false, defaultValue = "") String path, Pageable pageable, Model model) throws UnsupportedEncodingException { path = URLDecoder.decode(path, Constants.ENCODING); Sort sort = pageable.getSort(); String rootPath = sc.getRealPath(ROOT_DIR); File currentDirectory = new File(rootPath + File.separator + path); Map<Object, Object> current = extractFileInfoMap(currentDirectory, rootPath); current.put("name", currentDirectory.getName()); Map<Object, Object> parent = null; if (hasParent(currentDirectory, rootPath)) { File parentDirectory = currentDirectory.getParentFile(); parent = extractFileInfoMap(parentDirectory, rootPath); parent.put("name", parentDirectory.getName()); } List<Map<Object, Object>> files = Lists.newArrayList(); for (File subFile : currentDirectory.listFiles()) { files.add(extractFileInfoMap(subFile, rootPath)); } sort(files, sort); model.addAttribute("current", current); model.addAttribute("parent", parent); model.addAttribute("files", files); return viewName("list"); }
@Override public Page<Comment> search(CommentSearchRequest request, Pageable pageable) { FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager); QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Comment.class).get(); @SuppressWarnings("rawtypes") BooleanJunction<BooleanJunction> junction = qb.bool(); junction.must(qb.all().createQuery()); if (StringUtils.hasText(request.getKeyword())) { Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms"); String[] fields = new String[] {"authorName", "content"}; MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer); parser.setDefaultOperator(QueryParser.Operator.AND); Query query = null; try { query = parser.parse(request.getKeyword()); } catch (ParseException e1) { try { query = parser.parse(QueryParser.escape(request.getKeyword())); } catch (ParseException e2) { throw new RuntimeException(e2); } } junction.must(query); } if (StringUtils.hasText(request.getLanguage())) { junction.must( qb.keyword().onField("post.language").matching(request.getLanguage()).createQuery()); } if (request.getPostId() != null) { junction.must(qb.keyword().onField("post.id").matching(request.getPostId()).createQuery()); } if (request.getApproved() != null) { junction.must(qb.keyword().onField("approved").matching(request.getApproved()).createQuery()); } Query searchQuery = junction.createQuery(); Session session = (Session) entityManager.getDelegate(); Criteria criteria = session .createCriteria(Comment.class) .setFetchMode("post", FetchMode.JOIN) .setFetchMode("author", FetchMode.JOIN); Sort sort = null; if (pageable.getSort() != null) { if (pageable.getSort().getOrderFor("date") != null) { Order order = pageable.getSort().getOrderFor("date"); sort = new Sort( new SortField( "date", SortField.Type.STRING, order.getDirection().equals(Direction.DESC)), new SortField( "id", SortField.Type.LONG, order.getDirection().equals(Direction.DESC))); } } if (sort == null) { sort = new Sort( new SortField("date", SortField.Type.STRING), new SortField("id", SortField.Type.LONG)); } FullTextQuery persistenceQuery = fullTextEntityManager .createFullTextQuery(searchQuery, Comment.class) .setCriteriaQuery(criteria) .setSort(sort); persistenceQuery.setFirstResult(pageable.getOffset()); persistenceQuery.setMaxResults(pageable.getPageSize()); int resultSize = persistenceQuery.getResultSize(); @SuppressWarnings("unchecked") List<Comment> results = persistenceQuery.getResultList(); return new PageImpl<>(results, pageable, resultSize); }
// 動的条件に一致するEntityを全件検索 するサンプルを元に実装 // // http://terasolunaorg.github.io/guideline/5.0.1.RELEASE/ja/ArchitectureInDetail/DataAccessJpa.html#id21 @Override public Page<Result> findByCriteria(ResultCriteria criteria, Pageable pageable) { // collect dynamic conditions. final List<String> andConditions = new ArrayList<String>(); final List<String> joinConditions = new ArrayList<String>(); final Map<String, Object> bindParameters = new HashMap<String, Object>(); if (criteria.getStaffId() != null) { joinConditions.add("r.resultDetails rd"); andConditions.add("rd.staff.id = :staffId"); bindParameters.put("staffId", criteria.getStaffId()); } // TODO result の検索条件はここに書く // if (criteria.getStaffId() != null) { // andConditions.add("d.staffId = :staffId"); // bindParameters.put("staffId", criteria.getStaffId()); // } // if (!CollectionUtils.isEmpty(criteria.getStatusCodes())) { // andConditions.add("o.status.code IN :statusCodes"); // bindParameters.put("statusCodes", criteria.getStatusCodes()); // } // if (andConditions.isEmpty()) { // List<Result> Results = Collections.emptyList(); // return new PageImpl<Result>(Results, pageable, 0); // (3) // } // create dynamic query. final StringBuilder queryString = new StringBuilder(); final StringBuilder countQueryString = new StringBuilder(); // (4) final StringBuilder conditionsString = new StringBuilder(); // (4) queryString.append("select r FROM Result r "); countQueryString.append("SELECT COUNT(r) FROM Result r "); // (11) // add join conditions. for (String joinCondition : joinConditions) { conditionsString.append(" JOIN ").append(joinCondition); } // add conditions. Iterator<String> andConditionsIt = andConditions.iterator(); if (andConditionsIt.hasNext()) { conditionsString.append(" WHERE ").append(andConditionsIt.next()); } while (andConditionsIt.hasNext()) { conditionsString.append(" AND ").append(andConditionsIt.next()); } queryString.append(conditionsString); // (6) countQueryString.append(conditionsString); // (6) // add Result by condition. // (7) String query = QueryUtils.applySorting(queryString.toString(), pageable.getSort(), "r"); // create typed query. final TypedQuery<Long> countQuery = entityManager.createQuery(countQueryString.toString(), Long.class); // (8) final TypedQuery<Result> findQuery = entityManager.createQuery(query, Result.class); // bind parameters. for (Map.Entry<String, Object> bindParameter : bindParameters.entrySet()) { countQuery.setParameter(bindParameter.getKey(), bindParameter.getValue()); // (8) findQuery.setParameter(bindParameter.getKey(), bindParameter.getValue()); } long total = countQuery.getSingleResult().longValue(); // (9) List<Result> Results = null; if (total != 0) { // (10) findQuery.setFirstResult(pageable.getOffset()); findQuery.setMaxResults(pageable.getPageSize()); // execute query. Results = findQuery.getResultList(); } else { // (11) Results = Collections.emptyList(); } return new PageImpl<Result>(Results, pageable, total); // (12) }
/** * Creates a new {@link TypedQuery} from the given {@link Specification}. * * @param spec can be {@literal null}. * @param pageable can be {@literal null}. * @return */ private TypedQuery<M> getQuery(Specification<M> spec, Pageable pageable) { Sort sort = pageable == null ? null : pageable.getSort(); return getQuery(spec, sort); }
@Override public Page<DBObject> findPage( String collectionName, GroupPropertyFilter groupPropertyFilter, Pageable pageable, DBObject fields) { DB db = mongoClient.getDB(mongoDB); DBCollection dbColl = db.getCollection(collectionName); BasicDBObject query = new BasicDBObject(); List<BasicDBObject> andQueries = Lists.newArrayList(); List<PropertyFilter> filters = groupPropertyFilter.convertToPropertyFilters(); if (CollectionUtils.isNotEmpty(filters)) { // Query and Projection Operators: https://docs.mongodb.org/manual/reference/operator/query/ for (PropertyFilter filter : filters) { Object matchValue = filter.getMatchValue(); if (matchValue == null) { continue; } String[] propertyNames = filter.getConvertedPropertyNames(); List<BasicDBObject> orQueries = Lists.newArrayList(); for (String propertyName : propertyNames) { BasicDBObject queryItem = new BasicDBObject(); orQueries.add(queryItem); switch (filter.getMatchType()) { case EQ: queryItem.put(propertyName, matchValue); break; case NE: queryItem.put(propertyName, new BasicDBObject("$ne", matchValue)); break; case BK: List<BasicDBObject> orList = Lists.newArrayList(); orList.add(new BasicDBObject(propertyName, 0)); orList.add(new BasicDBObject(propertyName, "")); queryItem.put("$or", orList); break; case NB: queryItem.put(propertyName, new BasicDBObject("$regex", ".{1,}")); break; case NU: queryItem.put(propertyName, 0); break; case NN: queryItem.put(propertyName, 1); break; case CN: queryItem.put( propertyName, new BasicDBObject("$regex", ".*" + matchValue + ".*").append("$options", "i")); break; case NC: queryItem.put( propertyName, new BasicDBObject( "$not", new BasicDBObject("$regex", ".*" + matchValue + ".*") .append("$options", "i"))); break; case BW: queryItem.put( propertyName, new BasicDBObject("$regex", "^" + matchValue).append("$options", "i")); break; case BN: queryItem.put( propertyName, new BasicDBObject( "$not", new BasicDBObject("$regex", "^" + matchValue).append("$options", "i"))); break; case EW: queryItem.put( propertyName, new BasicDBObject("$regex", matchValue + "$").append("$options", "i")); break; case EN: queryItem.put( propertyName, new BasicDBObject( "$not", new BasicDBObject("$regex", matchValue + "$").append("$options", "i"))); break; case BT: Assert.isTrue(matchValue.getClass().isArray(), "Match value must be array"); Object[] matchValues = (Object[]) matchValue; Assert.isTrue(matchValues.length == 2, "Match value must have two value"); List<BasicDBObject> andList = Lists.newArrayList(); andList.add(new BasicDBObject(propertyName, new BasicDBObject("$gte", matchValue))); andList.add(new BasicDBObject(propertyName, new BasicDBObject("$gle", matchValue))); queryItem.put("$and", andList); break; case GT: queryItem.put(propertyName, new BasicDBObject("$gt", matchValue)); break; case GE: queryItem.put(propertyName, new BasicDBObject("$ge", matchValue)); break; case LT: queryItem.put(propertyName, new BasicDBObject("$lt", matchValue)); break; case LE: queryItem.put(propertyName, new BasicDBObject("$le", matchValue)); break; case IN: queryItem.put(propertyName, new BasicDBObject("$in", matchValue)); break; default: throw new UnsupportedOperationException( "Undefined PropertyFilter MatchType: " + filter.getMatchType()); } } if (orQueries.size() > 1) { andQueries.add(new BasicDBObject("$or", orQueries)); } else { andQueries.add(orQueries.get(0)); } } query = new BasicDBObject("$and", andQueries); } BasicDBObject sort = new BasicDBObject(); Sort pageSort = pageable.getSort(); if (pageSort != null) { Iterator<Order> orders = pageSort.iterator(); while (orders.hasNext()) { Order order = orders.next(); String prop = order.getProperty(); if (order.isAscending()) { sort.put(prop, 1); } else { sort.put(prop, -1); } } } DBCursor cur = dbColl .find(query, fields) .sort(sort) .skip(pageable.getOffset()) .limit(pageable.getPageSize()); List<DBObject> rows = Lists.newArrayList(); while (cur.hasNext()) { DBObject obj = cur.next(); rows.add(obj); } Page<DBObject> page = new PageImpl<DBObject>(rows, pageable, dbColl.count(query)); return page; }