org.springframework.data.domain.Sort.Order Java Examples
The following examples show how to use
org.springframework.data.domain.Sort.Order.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SysComnLogsService.java From danyuan-application with Apache License 2.0 | 7 votes |
/** * @param vo * 方法名: findAllError * 功 能: TODO(这里用一句话描述这个方法的作用) * 参 数: @return * 返 回: List<SysComnLogs> * 作 者 : Administrator * @throws */ public Page<SysComnLogs> findAllError(SysComnLogsVo vo) { // Example<SysComnLogs> example = Example.of(vo.getInfo()); Sort sort = Sort.by(new Order(Direction.DESC, "createTime")); PageRequest request = PageRequest.of(vo.getPageNumber() - 1, vo.getPageSize(), sort); Page<SysComnLogs> sourceCodes = sysComnLoggersDao.findAll(new Specification<SysComnLogs>() { /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ private static final long serialVersionUID = 1L; @Override public Predicate toPredicate(Root<SysComnLogs> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> list = new ArrayList<>(); list.add(cb.isNotNull(root.get("message").as(String.class))); return cb.and(list.toArray(new Predicate[list.size()])); } }, request); return sourceCodes; }
Example #2
Source File: IssueServiceTests.java From mirrorgate with Apache License 2.0 | 6 votes |
@Test public void getActiveUserStoriesByProjectNameTest() { final DashboardDTO dashboard = TestObjectFactory.createDashboard(); final Issue story1 = TestObjectFactory.createActiveStory(); final Issue story2 = TestObjectFactory.createActiveStory(); final List<Issue> stories = Arrays.asList(story1, story2); when(issueRepository.findActiveUserStoriesByBoards( Collections.singletonList(dashboard.getName()), Sort.by(Order.by("status"))) ).thenReturn(stories); final List<Issue> activeStoriesByDashboardName = issueService.getActiveUserStoriesByBoards(Collections.singletonList(dashboard.getName())); verify(issueRepository, times(1)).findActiveUserStoriesByBoards( Collections.singletonList(dashboard.getName()), Sort.by(Order.by("status")) ); assertThat(activeStoriesByDashboardName.get(0)).isEqualTo(story1); assertThat(activeStoriesByDashboardName.get(1)).isEqualTo(story2); }
Example #3
Source File: KeyValueQuerydslUtils.java From spring-data-keyvalue with Apache License 2.0 | 6 votes |
/** * Creates an {@link Expression} for the given {@link Order} property. * * @param order must not be {@literal null}. * @param builder must not be {@literal null}. * @return */ private static Expression<?> buildOrderPropertyPathFrom(Order order, PathBuilder<?> builder) { Assert.notNull(order, "Order must not be null!"); Assert.notNull(builder, "Builder must not be null!"); PropertyPath path = PropertyPath.from(order.getProperty(), builder.getType()); Expression<?> sortPropertyExpression = builder; while (path != null) { if (!path.hasNext() && order.isIgnoreCase()) { // if order is ignore-case we have to treat the last path segment as a String. sortPropertyExpression = Expressions.stringPath((Path<?>) sortPropertyExpression, path.getSegment()).lower(); } else { sortPropertyExpression = Expressions.path(path.getType(), (Path<?>) sortPropertyExpression, path.getSegment()); } path = path.next(); } return sortPropertyExpression; }
Example #4
Source File: DataInitializer.java From POC with Apache License 2.0 | 6 votes |
@EventListener(ContextRefreshedEvent.class) public void init() { log.info("start data initialization ..."); List<String> statements = Arrays.asList(// "DROP TABLE IF EXISTS reactive_posts;", "CREATE TABLE reactive_posts ( id SERIAL PRIMARY KEY, title VARCHAR(100) NOT NULL, content VARCHAR(100) NOT NULL);"); statements.forEach(query -> this.databaseClient.execute(query).then().block()); this.databaseClient.delete().from("reactive_posts").then() .and(this.databaseClient.insert().into("reactive_posts").value("title", "First post title") .value("content", "Content of my first post").map((r, m) -> r.get("id", Integer.class)).all() .log()) .thenMany(this.databaseClient.select().from("reactive_posts").orderBy(Sort.by(Order.desc("id"))) .as(ReactivePost.class).fetch().all().log()) .subscribe(post -> log.info("saving {}", post.toString()), e -> log.error(e.getMessage(), e), () -> log.info("initialization is done...")); }
Example #5
Source File: PageUtils.java From thymeleaf-spring-data-dialect with Apache License 2.0 | 6 votes |
/** * Creates an url to sort data by fieldName * * @param context execution context * @param fieldName field name to sort * @param forcedDir optional, if specified then only this sort direction will be allowed * @return sort URL */ public static String createSortUrl(final ITemplateContext context, final String fieldName, final Direction forcedDir) { // Params can be prefixed to manage multiple pagination on the same page final String prefix = getParamPrefix(context); final Collection<String> excludedParams = Arrays .asList(new String[] { prefix.concat(SORT), prefix.concat(PAGE) }); final String baseUrl = buildBaseUrl(context, excludedParams); final StringBuilder sortParam = new StringBuilder(); final Page<?> page = findPage(context); final Sort sort = page.getSort(); final boolean hasPreviousOrder = sort != null && sort.getOrderFor(fieldName) != null; if (forcedDir != null) { sortParam.append(fieldName).append(COMMA).append(forcedDir.toString().toLowerCase()); } else if (hasPreviousOrder) { // Sort parameters exists for this field, modify direction Order previousOrder = sort.getOrderFor(fieldName); Direction dir = previousOrder.isAscending() ? Direction.DESC : Direction.ASC; sortParam.append(fieldName).append(COMMA).append(dir.toString().toLowerCase()); } else { sortParam.append(fieldName); } return buildUrl(baseUrl, context).append(SORT).append(EQ).append(sortParam).toString(); }
Example #6
Source File: CmsController.java From hermes with Apache License 2.0 | 6 votes |
@RequestMapping("help-center/{cid}") public String helpCenterArticleCategory(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size, @PathVariable String cid, Model model) { List<Order> orders = new ArrayList<Order>(); orders.add(new Order(Direction.ASC, "order")); orders.add(new Order(Direction.DESC, "updateTime")); Pageable pageable = new PageRequest(page, size, new Sort(orders)); Page<Article> dataBox = articleService.find(cid, pageable); if (dataBox.getContent().size() == 1) { return "redirect:/help-center/" + cid + "/" + dataBox.getContent().get(0).getId(); } else { List<ArticleCategory> articleCategorys = articleCategoryRepository.findByLevel("二级"); for (ArticleCategory a : articleCategorys) { if (OTHER_KIND_LEVEL.equals(a.getCode())) { articleCategorys.remove(a); break; } } model.addAttribute("nav",HomeNav.HELP ); model.addAttribute("second", articleCategorys); model.addAttribute("sel", articleCategoryRepository.findOne(cid)); model.addAttribute("aeli", dataBox); return "cms/template_li"; } }
Example #7
Source File: KeyValueQuerydslUtils.java From spring-data-keyvalue with Apache License 2.0 | 6 votes |
/** * Transforms a plain {@link Order} into a QueryDsl specific {@link OrderSpecifier}. * * @param sort must not be {@literal null}. * @param builder must not be {@literal null}. * @return empty {@code OrderSpecifier<?>[]} when sort is {@literal null}. */ static OrderSpecifier<?>[] toOrderSpecifier(Sort sort, PathBuilder<?> builder) { Assert.notNull(sort, "Sort must not be null."); Assert.notNull(builder, "Builder must not be null."); List<OrderSpecifier<?>> specifiers = null; if (sort instanceof QSort) { specifiers = ((QSort) sort).getOrderSpecifiers(); } else { specifiers = new ArrayList<>(); for (Order order : sort) { specifiers.add(toOrderSpecifier(order, builder)); } } return specifiers.toArray(new OrderSpecifier<?>[specifiers.size()]); }
Example #8
Source File: SortUtility.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
/** * Parses the sort string e.g. given in a REST call based on the definition * of sorting: http://localhost/entity?s=field1:ASC, field2:DESC The fields * will be split into the keys of the returned map. The direction of the * sorting will be mapped into the {@link Direction} enum. * * @param enumType * the class of the enum which the fields in the sort string * should be related to. * @param <T> * the type of the enumeration which must be derived from * {@link FieldNameProvider} * @param sortString * the string representation of the query parameters. Might be * {@code null} or an empty string. * @return a list which holds the {@link FieldNameProvider} and the specific * {@link Direction} for them as a tuple. Never {@code null}. In * case of no sorting parameters an empty map will be returned. * @throws SortParameterSyntaxErrorException * if the sorting query parameter is not well-formed * @throws SortParameterUnsupportedFieldException * if a field name cannot be mapped to the enum type * @throws SortParameterUnsupportedDirectionException * if the given direction is not "ASC" or "DESC" */ public static <T extends Enum<T> & FieldNameProvider> List<Order> parse(final Class<T> enumType, final String sortString) throws SortParameterSyntaxErrorException { final List<Order> parsedSortings = new ArrayList<>(); // scan the sort tuples e.g. field:direction if (sortString != null) { final StringTokenizer tupleTokenizer = new StringTokenizer(sortString, DELIMITER_SORT_TUPLE); while (tupleTokenizer.hasMoreTokens()) { final String sortTuple = tupleTokenizer.nextToken().trim(); final StringTokenizer fieldDirectionTokenizer = new StringTokenizer(sortTuple, DELIMITER_FIELD_DIRECTION); if (fieldDirectionTokenizer.countTokens() == 2) { final String fieldName = fieldDirectionTokenizer.nextToken().trim().toUpperCase(); final String sortDirectionStr = fieldDirectionTokenizer.nextToken().trim(); final T identifier = getAttributeIdentifierByName(enumType, fieldName); final Direction sortDirection = getDirection(sortDirectionStr); parsedSortings.add(new Order(sortDirection, identifier.getFieldName())); } else { throw new SortParameterSyntaxErrorException(); } } } return parsedSortings; }
Example #9
Source File: PortfolioResponseServiceImpl.java From ExecDashboard with Apache License 2.0 | 6 votes |
/** * (non-Javadoc) * * @see com.capitalone.dashboard.executive.service.PortfolioResponseService#findAll() * @return * */ public List<PortfolioResponse> findAll() { List<ExecutiveSummaryList> executiveSummaryList = (List<ExecutiveSummaryList>) executiveSummaryListRepository .findAll(); List<String> eids = new ArrayList<>(); if (executiveSummaryList != null && !executiveSummaryList.isEmpty()) { for (ExecutiveSummaryList executiveSummary : executiveSummaryList) { eids.add(executiveSummary.getEid()); } if (!eids.isEmpty()) { Sort sort = new Sort(new Order(Direction.ASC, "order"), new Order(Direction.ASC, "executive.firstName")); return portfolioResponseRepository.getByEidsWithSort(eids, sort); } } return null; }
Example #10
Source File: PortfolioResponseServiceImpl.java From ExecDashboard with Apache License 2.0 | 6 votes |
/** * (non-Javadoc) * * @see com.capitalone.dashboard.executive.service.PortfolioResponseService#findByBusinessUnit(String) * @param businessUnit * @return */ @Override public List<PortfolioResponse> findByBusinessUnit(String businessUnit) { List<ExecutiveSummaryList> executiveSummaryList = executiveSummaryListRepository .findByBusinessUnits(businessUnit); List<String> eids = new ArrayList<>(); if (executiveSummaryList != null && !executiveSummaryList.isEmpty()) { for (ExecutiveSummaryList executiveSummary : executiveSummaryList) { eids.add(executiveSummary.getEid()); } if (!eids.isEmpty()) { Sort sort = new Sort(new Order(Direction.ASC, "order"), new Order(Direction.ASC, "executive.firstName")); return portfolioResponseRepository.getByEidsWithSort(eids, sort); } } return new ArrayList(); }
Example #11
Source File: SortUtils.java From MultimediaDesktop with Apache License 2.0 | 6 votes |
public static Sort covertSortDto(SortDto sortDto) { if (sortDto == null || sortDto.getOrders() == null || sortDto.getOrders().isEmpty()) { return null; } List<Order> orders = new ArrayList<>(); for (OrderDto orderdto : sortDto.getOrders()) { Order order = new Order(Sort.Direction.fromString(orderdto .getDirection().name()), orderdto.getProperty()); if (orderdto.isIgnoreCase()) { order = order.ignoreCase(); } orders.add(order); } return new Sort(orders); }
Example #12
Source File: SortParametersParserTest.java From springlets with Apache License 2.0 | 6 votes |
@Test public void validSortParsed() { // Prepare: ordering first with property3 and then with property1 parser = createParser( new String[] {"order[0][column]", "order[1][column]", "order[0][dir]", "order[1][dir]", "columns[0][data]", "columns[1][data]", "columns[2][data]", "columns[3][data]"}, new String[] {"3", "1", "asc", "desc", "property0", "property1", "property2", "property3"}); // Exercise Sort sort = parser.getSort(); Order order0 = sort.getOrderFor("property3"); Order order1 = sort.getOrderFor("property1"); // Verify assertThat(order0.getProperty()).as("Nombre de propiedad ordenada correcta") .isEqualTo("property3"); assertThat(order0.getDirection()).as("Dirección de ordenación de propiedad correcta") .isEqualTo(Direction.ASC); assertThat(order1.getProperty()).as("Nombre de propiedad ordenada correcta") .isEqualTo("property1"); assertThat(order1.getDirection()).as("Dirección de ordenación de propiedad correcta") .isEqualTo(Direction.DESC); }
Example #13
Source File: SortParametersParserTest.java From springlets with Apache License 2.0 | 6 votes |
@Test public void orderLoadedFromPosition() { // Prepare: ordering first with property3 and then with property1 parser = createParser( new String[] {"order[0][column]", "order[1][column]", "order[0][dir]", "order[1][dir]", "columns[0][data]", "columns[1][data]", "columns[2][data]", "columns[3][data]"}, new String[] {"3", "1", "asc", "desc", "property0", "property1", "property2", "property3"}); // Exercise Order order0 = parser.getOrderInPosition(0); Order order1 = parser.getOrderInPosition(1); // Verify assertThat(order0.getProperty()).as("Nombre de propiedad ordenada correcta") .isEqualTo("property3"); assertThat(order0.getDirection()).as("Dirección de ordenación de propiedad correcta") .isEqualTo(Direction.ASC); assertThat(order1.getProperty()).as("Nombre de propiedad ordenada correcta") .isEqualTo("property1"); assertThat(order1.getDirection()).as("Dirección de ordenación de propiedad correcta") .isEqualTo(Direction.DESC); }
Example #14
Source File: SysComnLogsService.java From danyuan-application with Apache License 2.0 | 6 votes |
/** * 方法名: findAllLongtime * 功 能: TODO(这里用一句话描述这个方法的作用) * 参 数: @param vo * 参 数: @return * 返 回: Page<SysComnLogs> * 作 者 : Administrator * @throws */ public Page<SysComnLogs> findAllLongtime(SysComnLogsVo vo) { Sort sort = Sort.by(new Order(Direction.DESC, "createTime")); PageRequest request = PageRequest.of(vo.getPageNumber() - 1, vo.getPageSize(), sort); Page<SysComnLogs> sourceCodes = sysComnLoggersDao.findAll(new Specification<SysComnLogs>() { /** * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么) */ private static final long serialVersionUID = 1L; @Override public Predicate toPredicate(Root<SysComnLogs> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> list = new ArrayList<>(); list.add(cb.gt((root.get("requestLong").as(Long.class)), 1000)); // list.add(cb.equal((root.get("url").as(String.class)), "/zhcx/findAllTableRow")); // list.add(cb.equal((root.get("classMethod").as(String.class)), "findAllTableRow")); return cb.and(list.toArray(new Predicate[list.size()])); } }, request); return sourceCodes; }
Example #15
Source File: DatatablesSortHandlerMethodArgumentResolver.java From springlets with Apache License 2.0 | 6 votes |
/** * Returns a full ordering criteria from the datatables parameters. * @return the ordering criteria */ public DatatablesSort getSort() { int columnCount = getColumnCount(); if (columnCount <= 0) { return null; } List<Order> orderList = new ArrayList<Order>(columnCount); for (int i = 0; i < columnCount; i++) { Order order = getOrderInPosition(i); if (order != null) { orderList.add(order); } } if (orderList.isEmpty()) { return null; } return new DatatablesSort(orderList); }
Example #16
Source File: AbstractPaginateList.java From plumdo-work with Apache License 2.0 | 6 votes |
@SuppressWarnings("rawtypes") private void setQueryOrder(Sort sort, Query query, Map<String, QueryProperty> properties) { if (sort == null || properties.isEmpty()) { return; } for (Order order : sort) { QueryProperty qp = properties.get(order.getProperty()); if (qp == null) { throw new FlowableIllegalArgumentException("Value for param 'sort' is not valid, '" + sort + "' is not a valid property"); } query.orderBy(qp); if (order.getDirection() == Direction.ASC) { query.asc(); } else { query.desc(); } } }
Example #17
Source File: PageableDataProvider.java From spring-data-provider with Apache License 2.0 | 6 votes |
private <T, F> Sort createSpringSort(Query<T, F> q) { List<QuerySortOrder> sortOrders; if (q.getSortOrders().isEmpty()) { sortOrders = getDefaultSortOrders(); } else { sortOrders = q.getSortOrders(); } List<Order> orders = sortOrders.stream() .map(PageableDataProvider::queryOrderToSpringOrder) .collect(Collectors.toList()); if (orders.isEmpty()) { return Sort.unsorted(); } else { return Sort.by(orders); } }
Example #18
Source File: PortfolioResponseServiceImpl.java From ExecDashboard with Apache License 2.0 | 6 votes |
/** * (non-Javadoc) * * @see com.capitalone.dashboard.executive.service.PortfolioResponseService#findByExecutivesHierarchy(String, * String) * @param businessUnit * @return */ @Override public List<PortfolioResponse> findByExecutivesHierarchy(String eid, String businessUnit) { List<String> reportingEids = new ArrayList<>(); ExecutiveHierarchy executivesHierarchy = executiveHierarchyRepository.findByEid(eid); if (executivesHierarchy != null) { Map<String, List<String>> reportees = executivesHierarchy.getReportees(); if (reportees != null && !reportees.isEmpty()) { if (!ALL.equalsIgnoreCase(businessUnit)) { reportingEids.addAll(reportees.get(businessUnit)); } else { for (Map.Entry<String, List<String>> entry : reportees.entrySet()) { reportingEids.addAll(entry.getValue()); } } } } if (!reportingEids.isEmpty()) { Sort sort = new Sort(new Order(Direction.ASC, "order"), new Order(Direction.ASC, "executive.firstName")); return portfolioResponseRepository.getByEidsWithSort(reportingEids, sort); } return new ArrayList(); }
Example #19
Source File: SysDicNameService.java From danyuan-application with Apache License 2.0 | 6 votes |
/** * 方法名: findkeyList * 功 能: TODO(这里用一句话描述这个方法的作用) * 参 数: @param code * 参 数: @return * 返 回: boolean * 作 者 : Administrator * @throws */ public List<SysDicKeyList> findkeyList(SysDicName info) { Example<SysDicName> example = Example.of(info); Optional<SysDicName> reinfo = sysDicNameDao.findOne(example); if (reinfo.isPresent()) { info = reinfo.get(); SysDicKeyList key = new SysDicKeyList(); key.setNameUuid(info.getUuid()); Example<SysDicKeyList> ke = Example.of(key); Order[] order = { new Order(Direction.ASC, "keyOrder"), new Order(Direction.ASC, "createTime") }; Sort sort = Sort.by(order); return sysDicKeyListDao.findAll(ke, sort); } else { return null; } }
Example #20
Source File: DatatablesSortHandlerMethodArgumentResolverTest.java From springlets with Apache License 2.0 | 5 votes |
/** * Unit test for the method {@link es.msssi.fwmvnje6.northwindjee.datatables.DatatablesSortHandlerMethodArgumentResolver#resolveArgument(org.springframework.core.MethodParameter, org.springframework.web.method.support.ModelAndViewContainer, org.springframework.web.context.request.NativeWebRequest, org.springframework.web.bind.support.WebDataBinderFactory)}. */ @Test public void checkValidSortIsResolved() throws Exception { // Prepare String[] paramNames = new String[] {"order[0][column]", "order[0][dir]", "columns[0][data]", "columns[1][data]", "columns[2][data]"}; String[] paramValues = new String[] {"1", "asc", "property0", "property1", "property2"}; HashMap<String, String[]> map = new HashMap<String, String[]>(paramNames.length); for (int i = 0; i < paramNames.length; i++) { String[] value = paramValues == null ? null : new String[] {paramValues[i]}; map.put(paramNames[i], value); } when(request.getParameterMap()).thenReturn(map); // Exercise Sort sort = resolver.resolveArgument(methodParameter, null, request, null); // Verify Order order0 = sort.getOrderFor("property1"); assertThat(order0.getProperty()).as("Valid property name to order by") .isEqualTo("property1"); assertThat(order0.getDirection()).as("Valir ordering direction for the property") .isEqualTo(Direction.ASC); }
Example #21
Source File: FirestoreRepositoryIntegrationTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void sortQueryTest() { Flux<User> users = Flux.fromStream(IntStream.range(1, 11).boxed()) .map(n -> new User("blah-person" + n, n)); this.userRepository.saveAll(users).blockLast(); List<String> pagedUsers = this.userRepository .findByAgeGreaterThan(7, Sort.by(Order.asc("age"))) .map(User::getName) .collectList() .block(); assertThat(pagedUsers).containsExactlyInAnyOrder( "blah-person8", "blah-person9", "blah-person10"); }
Example #22
Source File: FirestoreRepositoryIntegrationTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void pageableQueryTest() { Flux<User> users = Flux.fromStream(IntStream.range(1, 11).boxed()) .map(n -> new User("blah-person" + n, n)); this.userRepository.saveAll(users).blockLast(); PageRequest pageRequest = PageRequest.of(2, 3, Sort.by(Order.desc("age"))); List<String> pagedUsers = this.userRepository.findByAgeGreaterThan(0, pageRequest) .map(User::getName) .collectList() .block(); assertThat(pagedUsers).containsExactlyInAnyOrder( "blah-person4", "blah-person3", "blah-person2"); }
Example #23
Source File: PartTreeFirestoreQuery.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
/** * This method converts {@link org.springframework.data.domain.Sort.Order} * to {@link StructuredQuery.Order} for Firestore. */ private List<StructuredQuery.Order> createFirestoreSortOrders(Sort sort) { List<StructuredQuery.Order> sortOrders = new ArrayList<>(); for (Order order : sort) { if (order.isIgnoreCase()) { throw new IllegalArgumentException("Datastore does not support ignore case sort orders."); } // Get the name of the field to sort on String fieldName = this.persistentEntity.getPersistentProperty(order.getProperty()).getFieldName(); StructuredQuery.Direction dir = order.getDirection() == Direction.DESC ? StructuredQuery.Direction.DESCENDING : StructuredQuery.Direction.ASCENDING; FieldReference ref = FieldReference.newBuilder().setFieldPath(fieldName).build(); com.google.firestore.v1.StructuredQuery.Order firestoreOrder = com.google.firestore.v1.StructuredQuery.Order.newBuilder() .setField(ref) .setDirection(dir) .build(); sortOrders.add(firestoreOrder); } return sortOrders; }
Example #24
Source File: SpannerStatementQueryTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void sortTest() throws NoSuchMethodException { Object[] params = new Object[] { 8.88, Sort.by(Order.desc("traderId"), Order.asc("price"), Order.desc("action")) }; Method method = QueryHolder.class.getMethod("repositoryMethod6", Double.class, Sort.class); String expectedSql = "SELECT shares, trader_id, ticker, price, action, id " + "FROM trades WHERE ( price<@tag0 ) " + "ORDER BY trader_id DESC , price ASC , action DESC"; runPageableOrSortTest(params, method, expectedSql); }
Example #25
Source File: ContentServiceImpl.java From hermes with Apache License 2.0 | 5 votes |
/** * 内容管理查询结果 * * @author lishunfeng */ @Override public Page<Article> find(final String levelOne, final String levelTwo, final String levelThree, final String inputName, int page, int size) { // 初始化 List<Order> orders = new ArrayList<Order>(); orders.add(new Order(Direction.ASC, "order")); orders.add(new Order(Direction.DESC, "updateTime")); Pageable pageable = new PageRequest(page, size, new Sort(orders)); Page<Article> articleList = articleRepository.findAll(new Specification<Article>() { @Override public Predicate toPredicate(Root<Article> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> p = new ArrayList<Predicate>(); if (StringUtils.isNotEmpty(levelOne) && StringUtils.isEmpty(levelTwo)) { p.add(cb.equal(root.<ArticleCategory> get("category").<String> get("id"), levelOne)); } if (StringUtils.isNotEmpty(levelTwo) && StringUtils.isEmpty(levelThree)) { p.add(cb.equal(root.<ArticleCategory> get("category").<String> get("id"), levelTwo)); } if (StringUtils.isNotEmpty(levelThree)) { p.add(cb.equal(root.<ArticleCategory> get("category").<String> get("id"), levelThree)); } if (StringUtils.isNotEmpty(inputName)) { p.add(cb.like(root.<String> get("articleTitle"), "%" + inputName + "%")); } query.where(cb.and(p.toArray(new Predicate[p.size()]))); return query.getRestriction(); } }, pageable); return articleList; }
Example #26
Source File: JdbcClient.java From plumdo-work with Apache License 2.0 | 5 votes |
private String getOrderBySql(Sort sort) { StringBuilder orderBy = new StringBuilder(" ORDER BY "); for (Order order : sort) { orderBy.append("`").append(order.getProperty()).append("` ").append(order.getDirection().toString()).append(","); } orderBy.delete(orderBy.length() - 1, orderBy.length()); return orderBy.toString(); }
Example #27
Source File: DefaultQueryParser.java From dubbox with Apache License 2.0 | 5 votes |
/** * Append sorting parameters to * {@link org.apache.solr.client.solrj.SolrQuery} * * @param solrQuery * @param sort */ protected void appendSort(SolrQuery solrQuery, Sort sort) { if (sort == null) { return; } for (Order order : sort) { solrQuery.addSort(order.getProperty(), order.isAscending() ? ORDER.asc : ORDER.desc); } }
Example #28
Source File: HazelcastSortAccessor.java From spring-data-hazelcast with Apache License 2.0 | 5 votes |
/** * <p> * Sort on a sequence of fields, possibly none. * </P> * * @param query If not null, will contain one of more {@link Sort.Order} objects. * @return A sequence of comparators or {@code null} */ public Comparator<Entry<?, ?>> resolve(KeyValueQuery<?> query) { if (query == null || query.getSort() == Sort.unsorted()) { return null; } Comparator hazelcastPropertyComparator = null; for (Order order : query.getSort()) { if (order.getProperty().indexOf('.') > -1) { throw new UnsupportedOperationException("Embedded fields not implemented: " + order); } if (order.isIgnoreCase()) { throw new UnsupportedOperationException("Ignore case not implemented: " + order); } if (NullHandling.NATIVE != order.getNullHandling()) { throw new UnsupportedOperationException("Null handling not implemented: " + order); } if (hazelcastPropertyComparator == null) { hazelcastPropertyComparator = new HazelcastPropertyComparator(order.getProperty(), order.isAscending()); } else { hazelcastPropertyComparator = hazelcastPropertyComparator.thenComparing( new HazelcastPropertyComparator(order.getProperty(), order.isAscending())); } } return hazelcastPropertyComparator; }
Example #29
Source File: SortUtil.java From cloudstreetmarket.com with GNU General Public License v3.0 | 5 votes |
public static Sort buildSort(List<String> fields, List<String> directions){ List<Order> result = new LinkedList<>(); for (int i = 0; i < fields.size(); i++) { if(directions.get(i) == null){ result.add(new Order(fields.get(i))); } else{ result.add(new Order(Direction.fromString(directions.get(i)), fields.get(i))); } } return new Sort(result); }
Example #30
Source File: ArtifactsRestController.java From scava with Eclipse Public License 2.0 | 5 votes |
@ApiOperation(value = "Search artifact to KB") @RequestMapping(value = "search/{artifact_query}", produces = { "application/json", "application/xml" }, method = RequestMethod.GET) @ApiImplicitParams({ // FIXME @ApiImplicitParam(name = "page", dataType = "integer", paramType = "query", value = "Results page you want to retrieve (0..N)"), @ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", value = "Number of records per page."), @ApiImplicitParam(name = "sort", dataType = "string", paramType = "query", value = "Sorting criteria in the format: [asc|desc]") }) public @ResponseBody List<Artifact> getProject(@PathVariable("artifact_query") String projectQuery, @RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "size", defaultValue = "10") int size, @RequestParam(value = "sort", defaultValue = "asc") String sort) { PageRequest pr = new PageRequest(page, size, new Sort(Arrays.asList( sort.equalsIgnoreCase("ASC") ? new Order(Direction.ASC, "temp") : new Order(Direction.DESC, "temp")))); return recommenderManager.getArtifactsByQuery(projectQuery, pr); }