Java Code Examples for org.springframework.data.domain.Sort#by()

The following examples show how to use org.springframework.data.domain.Sort#by() . These examples are extracted from open source projects. 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
/**
 * 用户查询.
 *
 * @return
 */
@RequestMapping("/list")
@RequiresPermissions("admin:view")//权限管理;
public ModelAndView userInfo(@RequestParam(value = "start", defaultValue = "0") Integer start,
                             @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
    start = start < 0 ? 0 : start;
    Sort sort = Sort.by(Sort.Order.desc("uid"));
    Pageable pageable = new PageRequest(start, limit, sort);

    Page<Admin> page = adminDao.findAll(pageable);
    //session 由controller 注入参数传入
    Admin adminprincipal = (Admin) SecurityUtils.getSubject().getPrincipal();
    //String loginName = (String) SecurityUtils.getSubject().getPrincipal();
    ModelAndView modelAndView = new ModelAndView("list");
    modelAndView.addObject("page", page);
    modelAndView.addObject("name", adminprincipal.getName());
    modelAndView.addObject("Username", adminprincipal.getUsername());
    modelAndView.addObject("RoleList", adminprincipal.getRoleList());
    return modelAndView;
}
 
Example 2
Source Project: jbone   File: SpecificationUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 构建排序
 * @param sortDOS s
 * @return r
 */
public static Sort buildSort(List<SearchSortDO> sortDOS){
    Sort sort = null;
    //构建排序
    if(!CollectionUtils.isEmpty(sortDOS)){
        List<Sort.Order> orders = new ArrayList<>();
        for (SearchSortDO sortDO: sortDOS) {
            Sort.Order order = null;
            if(sortDO.getDirection() == SearchSortDO.Direction.ASC){
                order = Sort.Order.asc(sortDO.getProperty());
            }else{
                order = Sort.Order.desc(sortDO.getProperty());
            }
            orders.add(order);
        }
        sort = Sort.by(orders);
    }else{
        sort = Sort.unsorted();
    }
    return sort;
}
 
Example 3
/**
 * 方法名: 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 4
Source Project: oauth2-server   File: LoginHistoryServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public JsonObjects<LoginHistory> listByUsername(String username, int pageNum, int pageSize, String sortField, String sortOrder) {
    JsonObjects<LoginHistory> jsonObjects = new JsonObjects<>();
    Sort sort;
    if (StringUtils.equalsIgnoreCase(sortOrder, "asc")) {
        sort = Sort.by(Sort.Direction.ASC, sortField);
    } else {
        sort = Sort.by(Sort.Direction.DESC, sortField);
    }
    Pageable pageable = PageRequest.of(pageNum - 1, pageSize, sort);
    Page<LoginHistoryEntity> page = loginHistoryRepository.findByUsername(username, pageable);
    if (page.getContent() != null && page.getContent().size() > 0) {
        jsonObjects.setRecordsTotal(page.getTotalElements());
        jsonObjects.setRecordsFiltered(page.getTotalElements());
        page.getContent().forEach(u -> jsonObjects.getData().add(dozerMapper.map(u, LoginHistory.class)));
    }
    return jsonObjects;
}
 
Example 5
/**
 * 方法名: 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 6
@Test
public void testFindSortWithAnd() {
    final Sort sort = Sort.by(Sort.Direction.ASC, "forkCount");
    final List<SortedProject> projects = Lists.newArrayList(repository.findByNameAndCreator(NAME_0, CREATOR_0,
        sort));
    final List<SortedProject> references = Arrays.asList(PROJECT_0);

    references.sort(Comparator.comparing(SortedProject::getStarCount));

    Assert.assertEquals(references.size(), projects.size());
    Assert.assertEquals(references, projects);
}
 
Example 7
Source Project: spring-data-cosmosdb   File: CosmosTemplateIT.java    License: MIT License 5 votes vote down vote up
@Test
public void testFindAllWithTwoPagesAndVerifySortOrder() {
    final Person testPerson4 = new Person("id_4", "barney", NEW_LAST_NAME, HOBBIES, ADDRESSES);
    final Person testPerson5 = new Person("id_5", "fred", NEW_LAST_NAME, HOBBIES, ADDRESSES);

    cosmosTemplate.insert(TEST_PERSON_2,
            new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_2)));
    cosmosTemplate.insert(TEST_PERSON_3,
            new PartitionKey(personInfo.getPartitionKeyFieldValue(TEST_PERSON_3)));
    cosmosTemplate.insert(testPerson4,
            new PartitionKey(personInfo.getPartitionKeyFieldValue(testPerson4)));
    cosmosTemplate.insert(testPerson5,
            new PartitionKey(personInfo.getPartitionKeyFieldValue(testPerson5)));

    final Sort sort = Sort.by(Sort.Direction.ASC, "firstName");
    final PageRequest pageRequest = new CosmosPageRequest(0, PAGE_SIZE_3, null, sort);

    final Page<Person> firstPage = cosmosTemplate.findAll(pageRequest, Person.class,
        containerName);

    assertThat(firstPage.getContent().size()).isEqualTo(3);
    validateNonLastPage(firstPage, firstPage.getContent().size());

    final List<Person> firstPageResults = firstPage.getContent();
    assertThat(firstPageResults.get(0).getFirstName()).isEqualTo(testPerson4.getFirstName());
    assertThat(firstPageResults.get(1).getFirstName()).isEqualTo(FIRST_NAME);
    assertThat(firstPageResults.get(2).getFirstName()).isEqualTo(testPerson5.getFirstName());

    final Page<Person> secondPage = cosmosTemplate.findAll(firstPage.getPageable(), Person.class,
        containerName);

    assertThat(secondPage.getContent().size()).isEqualTo(2);
    validateLastPage(secondPage, secondPage.getContent().size());

    final List<Person> secondPageResults = secondPage.getContent();
    assertThat(secondPageResults.get(0).getFirstName()).isEqualTo(NEW_FIRST_NAME);
    assertThat(secondPageResults.get(1).getFirstName()).isEqualTo(NEW_FIRST_NAME);
}
 
Example 8
@Override
public List<EvaluationVo> getAllEvaluations(Integer productId,Integer pageNum,Integer pageSize) {
    List<EvaluationVo> evaluationVos=Lists.newArrayList();
    Sort.Order order=new Sort.Order(Sort.Direction.DESC,"evaluationTime");
    Sort sort=Sort.by(Lists.newArrayList(order));
    evaluationRepository.findByProductId(productId, PageRequest.of(pageNum-1,pageSize,sort)).forEach(purchaseEvaluation -> {
        EvaluationVo evaluationVo=new EvaluationVo();
        BeanUtils.copyProperties(purchaseEvaluation,evaluationVo);
        evaluationVos.add(evaluationVo);
    });
    return evaluationVos;
}
 
Example 9
@Test // #292
void sortsByPropertyOfCustomOrder() {

	UserAccount account = users.create("user", UnencryptedPassword.of("password"));
	CustomOrder first = orders.save(new CustomOrder(account, "first"));
	CustomOrder second = orders.save(new CustomOrder(account, "second"));

	var sort = Sort.by("customProperty");

	assertThat(orders.findAll(getFirstPage(sort.ascending()))).containsExactly(first, second);
	assertThat(orders.findAll(getFirstPage(sort.descending()))).containsExactly(second, first);
}
 
Example 10
@Test(expected = IllegalArgumentException.class)
public void testFindAllSortIgnoreCaseException() {
    final Sort.Order order = Sort.Order.by("name").ignoreCase();
    final Sort sort = Sort.by(order);

    this.repository.findAll(sort);
}
 
Example 11
@Test
public void findAllPageableByExampleTest() {
	final List<Customer> toBeRetrieved = new LinkedList<>();
	toBeRetrieved.add(new Customer("A", "Z", 0));
	toBeRetrieved.add(new Customer("B", "X", 0));
	toBeRetrieved.add(new Customer("B", "Y", 0));
	toBeRetrieved.add(new Customer("C", "V", 0));
	toBeRetrieved.add(new Customer("D", "T", 0));
	toBeRetrieved.add(new Customer("D", "U", 0));
	toBeRetrieved.add(new Customer("E", "S", 0));
	toBeRetrieved.add(new Customer("F", "P", 0));
	toBeRetrieved.add(new Customer("F", "Q", 0));
	toBeRetrieved.add(new Customer("F", "R", 0));
	repository.saveAll(toBeRetrieved);
	repository.save(new Customer("A", "A", 1));
	final Example<Customer> example = Example.of(new Customer("", "", 0),
		ExampleMatcher.matchingAny().withIgnoreNullValues().withIgnorePaths(new String[] { "location", "alive" }));
	final List<Sort.Order> orders = new LinkedList<>();
	orders.add(new Sort.Order(Sort.Direction.ASC, "name"));
	orders.add(new Sort.Order(Sort.Direction.ASC, "surname"));
	final Sort sort = Sort.by(orders);
	final int pageNumber = 1;
	final int pageSize = 3;
	final Page<Customer> retrievedPage = repository.findAll(example, PageRequest.of(pageNumber, pageSize, sort));
	assertEquals(toBeRetrieved.size(), retrievedPage.getTotalElements());
	assertEquals(pageNumber, retrievedPage.getNumber());
	assertEquals(pageSize, retrievedPage.getSize());
	assertEquals((toBeRetrieved.size() + pageSize - 1) / pageSize, retrievedPage.getTotalPages());
	final List<Customer> expected = toBeRetrieved.subList(pageNumber * pageSize, (pageNumber + 1) * pageSize);
	assertTrue(equals(expected, retrievedPage, cmp, eq, true));
}
 
Example 12
@Test
public void ambiguousSort() throws NoSuchMethodException {
	queryWithMockResult("findByActionAndSymbolAndPriceLessThanAndPriceGreater"
			+ "ThanEqualAndIdIsNullOrderByIdDesc", null,
			getClass().getMethod("tradeMethod", String.class, String.class, double.class, double.class,
					Sort.class));

	Object[] params = new Object[] { "BUY", "abcd", 8.88, 3.33, Sort.by(Sort.Direction.ASC, "price") };

	when(this.datastoreTemplate.queryKeysOrEntities(any(), any())).thenAnswer((invocation) -> {
		EntityQuery statement = invocation.getArgument(0);

		EntityQuery expected = StructuredQuery.newEntityQueryBuilder()
				.setFilter(FILTER)
				.setKind("trades")
				.setOrderBy(OrderBy.desc("__key__"), OrderBy.asc("price")).build();

		assertThat(statement).isEqualTo(expected);

		return EMPTY_RESPONSE;
	});

	when(this.queryMethod.getCollectionReturnType()).thenReturn(List.class);

	this.partTreeDatastoreQuery.execute(params);
	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), any());
}
 
Example 13
@Test(expected = CosmosDBAccessException.class)
public void testFindAllSortMoreThanOneOrderException() {
    final Sort sort = Sort.by(Sort.Direction.ASC, "name", "creator");

    this.repository.findAll(sort);
}
 
Example 14
@Test
public void sortParamQueryTest() throws NoSuchMethodException {

	String sql = "SELECT * FROM :org.springframework.cloud.gcp.data.spanner.repository.query.SqlSpannerQueryTests$Child:"
			+ " WHERE id = @id AND trader_id = @trader_id";
	// @formatter:off
	String entityResolvedSql = "SELECT *, " +
			"ARRAY (SELECT AS STRUCT canceled, documentId, id, childId, content " +
				"FROM documents WHERE (documents.id = children.id AND documents.childId = children.childId) " +
					"AND (canceled = false)) AS documents " +
			"FROM (SELECT * FROM children WHERE id = @id AND trader_id = @trader_id) children " +
			"WHERE disabled = false ORDER BY trader_id ASC";
	// @formatter:on

	Object[] params = new Object[] { "ID", "TRADER_ID", Sort.by(Order.asc("trader_id"))};
	String[] paramNames = new String[] { "id", "trader_id", "ignoredSort" };

	when(queryMethod.isCollectionQuery()).thenReturn(false);
	when(queryMethod.getReturnedObjectType()).thenReturn((Class) Child.class);

	EvaluationContext evaluationContext = new StandardEvaluationContext();
	for (int i = 0; i < params.length; i++) {
		evaluationContext.setVariable(paramNames[i], params[i]);
	}
	when(this.evaluationContextProvider.getEvaluationContext(any(), any()))
			.thenReturn(evaluationContext);

	SqlSpannerQuery sqlSpannerQuery = createQuery(sql, Child.class, false);

	doAnswer((invocation) -> {
		Statement statement = invocation.getArgument(0);
		SpannerQueryOptions queryOptions = invocation.getArgument(1);
		assertThat(queryOptions.isAllowPartialRead()).isTrue();

		assertThat(statement.getSql()).isEqualTo(entityResolvedSql);

		Map<String, Value> paramMap = statement.getParameters();

		assertThat(paramMap.get("id").getString()).isEqualTo(params[0]);
		assertThat(paramMap.get("trader_id").getString()).isEqualTo(params[1]);
		assertThat(paramMap.get("ignoredSort")).isNull();

		return null;
	}).when(this.spannerTemplate).executeQuery(any(), any());

	// This dummy method was created so the metadata for the ARRAY param inner type is
	// provided.
	Method method = QueryHolder.class.getMethod("dummyMethod5", String.class, String.class, Sort.class);
	when(this.queryMethod.getMethod()).thenReturn(method);
	Mockito.<Parameters>when(this.queryMethod.getParameters()).thenReturn(new DefaultParameters(method));

	sqlSpannerQuery.execute(params);

	verify(this.spannerTemplate, times(1)).executeQuery(any(), any());
}
 
Example 15
Source Project: spring-data-hazelcast   File: QueryIT.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void findByFirstnameWithSort() {
    Person jackNicholson1975 = new Person();
    jackNicholson1975.setId("1975");
    jackNicholson1975.setFirstname("Jack");
    jackNicholson1975.setLastname("Nicholson");
    this.personMap.put(jackNicholson1975.getId(), jackNicholson1975);

    Person jackLemmon = new Person();
    jackLemmon.setId("1973");
    jackLemmon.setFirstname("Jack");
    jackLemmon.setLastname("Lemmon");
    this.personMap.put(jackLemmon.getId(), jackLemmon);

    Person jackNicholson1997 = new Person();
    jackNicholson1997.setId("1997");
    jackNicholson1997.setFirstname("Jack");
    jackNicholson1997.setLastname("Nicholson");
    this.personMap.put(jackNicholson1997.getId(), jackNicholson1997);

    List<Person> matches = this.personRepository.findByFirstname("Jack", null);
    assertThat("NULL 2 x Nicholson and 1 x Lemmon", matches.size(), equalTo(3));
    assertThat("NULL sort", matches,
            containsInAnyOrder(hasProperty("id", equalTo("1973")), hasProperty("id", equalTo("1975")),
                    hasProperty("id", equalTo("1997"))));

    Sort sort = Sort.by(Sort.Direction.DESC, "id");
    matches = this.personRepository.findByFirstname("Jack", sort);

    assertThat("DESC 2 x Nicholson and 1 x Lemmon", matches.size(), equalTo(3));
    assertThat("DESC 1st", matches.get(0).getId(), equalTo("1997"));
    assertThat("DESC 2nd", matches.get(1).getId(), equalTo("1975"));
    assertThat("DESC 3rd", matches.get(2).getId(), equalTo("1973"));

    sort = Sort.by(Sort.Direction.ASC, "id");
    matches = this.personRepository.findByFirstname("Jack", sort);

    assertThat("ASC 2 x Nicholson and 1 x Lemmon", matches.size(), equalTo(3));
    assertThat("ASC 1st", matches.get(0).getId(), equalTo("1973"));
    assertThat("ASC 2nd", matches.get(1).getId(), equalTo("1975"));
    assertThat("ASC 3rd", matches.get(2).getId(), equalTo("1997"));
}
 
Example 16
@Test // DATACMNS-525
public void toOrderSpecifierConvertsSimpleDescSortCorrectly() {

	Sort sort = Sort.by(Direction.DESC, "firstname");

	OrderSpecifier<?>[] specifiers = toOrderSpecifier(sort, builder);

	assertThat(specifiers).containsExactly(QPerson.person.firstname.desc());
}
 
Example 17
@Test
public void pageableTestSort() {

	String gql = "SELECT * FROM trades WHERE [email protected]";

	Object[] paramVals = new Object[] {1, Sort.by(Sort.Order.asc("p1"), Sort.Order.desc("p2"))};

	String[] paramNames = new String[] { "price", null };

	Parameters parameters = buildParameters(paramVals, paramNames);

	when(parameters.hasSortParameter()).thenReturn(true);
	when(parameters.getSortIndex()).thenReturn(1);

	GqlDatastoreQuery gqlDatastoreQuery = createQuery(gql, false, false);

	doAnswer((invocation) -> {
		GqlQuery statement = invocation.getArgument(0);

		assertThat(statement.getQueryString())
				.isEqualTo("SELECT * FROM trades WHERE [email protected] ORDER BY p1 ASC, p2 DESC");

		Map<String, Value> paramMap = statement.getNamedBindings();

		assertThat(paramMap.get("price").get()).isEqualTo(1L);

		return null;
	}).when(this.datastoreTemplate).queryKeysOrEntities(any(), eq(Trade.class));

	doReturn(false).when(gqlDatastoreQuery).isNonEntityReturnedType(any());

	gqlDatastoreQuery.execute(paramVals);

	verify(this.datastoreTemplate, times(1))
			.queryKeysOrEntities(any(), eq(Trade.class));
}
 
Example 18
@Test // DATACMNS-525
public void toOrderSpecifierConvertsSimpleAscSortCorrectly() {

	Sort sort = Sort.by(Direction.ASC, "firstname");

	OrderSpecifier<?>[] specifiers = toOrderSpecifier(sort, builder);

	assertThat(specifiers).containsExactly(QPerson.person.firstname.asc());
}
 
Example 19
/**
 * 方法名 : findAllBySearchText
 * 功 能 : TODO(这里用一句话描述这个方法的作用)
 * 参 数 : @param pageNumber
 * 参 数 : @param pageSize
 * 参 数 : @param info
 * 参 数 : @return
 * 参 考 : @see
 * tk.ainiyue.danyuan.application.softm.system.service.SysSystemService#findAllBySearchText(int,
 * int, tk.ainiyue.danyuan.application.softm.system.po.SysSystemInfo)
 * 作 者 : Administrator
 */

public Page<SysSystemInfo> findAllBySearchText(int pageNumber, int pageSize, SysSystemInfo info) {
	Example<SysSystemInfo> example = Example.of(info);
	Sort sort = Sort.by(new Order(Direction.DESC, "insertDatetime"));
	PageRequest request = PageRequest.of(pageNumber - 1, pageSize, sort);
	Page<SysSystemInfo> sourceCodes = sysSystemDao.findAll(example, request);
	return sourceCodes;
}
 
Example 20
/**
 * Get default {@link Sort}.
 *
 * @return {@link Sort}
 */
public static Sort getDefaultSort() {
  return Sort.by(Direction.ASC, "id");
}