org.springframework.data.domain.Sort Java Examples

The following examples show how to use org.springframework.data.domain.Sort. 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: FirestoreRepositoryTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void testSortQuery() {
	userRepository.findByAgeGreaterThan(0, Sort.by("name")).blockLast();

	ArgumentCaptor<StructuredQuery.Builder> captor =
			ArgumentCaptor.forClass(StructuredQuery.Builder.class);
	verify(template).execute(captor.capture(), eq(User.class));

	StructuredQuery.Builder result = captor.getValue();
	assertThat(result.getOrderByList()).containsExactly(
			Order.newBuilder()
					.setDirection(Direction.ASCENDING)
					.setField(
							FieldReference.newBuilder().setFieldPath("name"))
					.build());
}
 
Example #2
Source File: MerchantService.java    From runscore with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
public PageResult<MerchantVO> findMerchantByPage(MerchantQueryCondParam param) {
	Specification<Merchant> spec = new Specification<Merchant>() {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public Predicate toPredicate(Root<Merchant> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
			List<Predicate> predicates = new ArrayList<Predicate>();
			if (StrUtil.isNotBlank(param.getName())) {
				predicates.add(builder.equal(root.get("name"), param.getName()));
			}
			return predicates.size() > 0 ? builder.and(predicates.toArray(new Predicate[predicates.size()])) : null;
		}
	};
	Page<Merchant> result = merchantRepo.findAll(spec,
			PageRequest.of(param.getPageNum() - 1, param.getPageSize(), Sort.by(Sort.Order.desc("createTime"))));
	PageResult<MerchantVO> pageResult = new PageResult<>(MerchantVO.convertFor(result.getContent()),
			param.getPageNum(), param.getPageSize(), result.getTotalElements());
	return pageResult;
}
 
Example #3
Source File: RiskService.java    From OpenLRW with Educational Community License v2.0 6 votes vote down vote up
/**
 * Get RiskScore for a user and a class given
 *
 * @param tenantId
 * @param orgId
 * @param classId
 * @param userId
 * @param date : format 'yyyy-mm-dd' or keyword 'latest'
 * @return Collection<MongoRisk>
 */
public Collection<MongoRisk> getRisksForUserAndClass(
        final String tenantId, final String orgId, final String classId,
        final String userId, final String date, final int limit
){
    if (StringUtils.isBlank(tenantId) || StringUtils.isBlank(orgId) || StringUtils.isBlank(userId) || StringUtils.isBlank(classId))
        throw new IllegalArgumentException();

    Collection<MongoRisk> mongoRisks;

    Query query = new Query();
    query.with(Sort.by("dateTime").descending()); // Order by date: the most recent
    query.addCriteria(where("userSourcedId").is(userId).and("classSourcedId").is(classId).and("orgId").is(orgId).and("tenantId").is(tenantId));

    if (limit > 0)
        query.limit(limit);

    this.dayCriteria(query, date);

    mongoRisks = mongoOps.find(query, MongoRisk.class);

    if (!mongoRisks.isEmpty())
        return new ArrayList<>(mongoRisks);

    throw new OneRosterNotFoundException("Risks not found.");
}
 
Example #4
Source File: EventController.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "getNewBlockEventInfo",
        notes = "get registered NewBlockEvent info by page")
@GetMapping(value = {"newBlockEvent/list/{groupId}/{pageNumber}/{pageSize}",
        "newBlockEvent/list/{groupId}"})
public BasePageResponse getNewBlockEventInfo(@PathVariable("groupId") Integer groupId,
                                             @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                                             @PathVariable(value = "pageSize", required = false) Integer pageSize) {
    log.debug("start getNewBlockEventInfo. groupId:{}", groupId);
    List<NewBlockEventInfo> resList;
    if (pageNumber == null || pageSize == null) {
         resList = eventService.getNewBlockInfoList(groupId);
    } else {
        if (pageNumber < 1) {
            return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0);
        }
        Pageable pageable = new PageRequest(pageNumber - 1, pageSize,
                new Sort(Sort.Direction.DESC, "createTime"));
        resList = eventService.getNewBlockInfoList(groupId, pageable);
    }
    log.debug("end getNewBlockEventInfo resList count. {}", resList.size());
    return new BasePageResponse(ConstantCode.RET_SUCCESS, resList, resList.size());
}
 
Example #5
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
@Test
void findWithPageable(@Autowired ReactivePersonRepository repository) {

	Sort sort = Sort.by("name");
	int page = 0;
	int limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person1))
		.verifyComplete();


	sort = Sort.by("name");
	page = 1;
	limit = 1;

	StepVerifier.create(repository.findByNameStartingWith("Test", PageRequest.of(page, limit, sort)))
		.assertNext(person -> assertThat(person).isEqualTo(person2))
		.verifyComplete();
}
 
Example #6
Source File: ReviewRepositoryImpl.java    From mirrorgate with Apache License 2.0 6 votes vote down vote up
@Override
public List<ApplicationReviewsDTO> getLastReviewPerApplication(final List<String> names) {

    final Aggregation aggregation = newAggregation(
        match(Criteria.where("appname").in(names)),
        sort(Sort.by(DESC, "timestamp")),
        group("appname", "platform")
            .first("platform").as("platform")
            .first("appname").as("appName")
            .first("appname").as("appId")
            .first("commentId").as("commentId")
    );

    //Convert the aggregation result into a List
    final AggregationResults<ApplicationReviewsDTO> groupResults
        = mongoTemplate.aggregate(aggregation, Review.class, ApplicationReviewsDTO.class);

    return groupResults.getMappedResults();
}
 
Example #7
Source File: TargetFilterBeanQuery.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 *
 * @param definition
 * @param queryConfig
 * @param sortPropertyIds
 * @param sortStates
 */
public TargetFilterBeanQuery(final QueryDefinition definition, final Map<String, Object> queryConfig,
        final Object[] sortPropertyIds, final boolean[] sortStates) {
    super(definition, queryConfig, sortPropertyIds, sortStates);
    if (HawkbitCommonUtil.isNotNullOrEmpty(queryConfig)) {
        searchText = (String) queryConfig.get(SPUIDefinitions.FILTER_BY_TEXT);
        if (!StringUtils.isEmpty(searchText)) {
            searchText = String.format("%%%s%%", searchText);
        }
    }

    if (sortStates != null && sortStates.length > 0) {
        // Initalize sort
        sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[0]);
        // Add sort
        for (int tfId = 1; tfId < sortPropertyIds.length; tfId++) {
            sort.and(new Sort(sortStates[tfId] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[tfId]));
        }
    }
}
 
Example #8
Source File: WxAccountFansServiceImpl.java    From cms with Apache License 2.0 6 votes vote down vote up
@Override
public Page<WxAccountFans> getAccountFans(Integer page, int size, WxAccountFans query, Long tagId) {
    Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
    return fansRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
        List<Predicate> predicates = new ArrayList<>();
        if (tagId != null && tagId > 0) {
            Join<WxAccountFans, WxFansTag> tagsJoin = root.join("fansTags", JoinType.LEFT);
            predicates.add(criteriaBuilder.equal(tagsJoin.get("tagId"), tagId));
            criteriaQuery.distinct(true);
        }
        if (StringUtils.isNotBlank(query.getNickName())) {
            predicates.add(criteriaBuilder.like(root.get("nickName"), query.getNickName() + "%"));
        }

        return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
    }, pageable);
}
 
Example #9
Source File: DefaultNotificationManager.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
public PageRequest getPageRequestForNotifications(Integer pageNumber, Integer pageSize, String sortField, String sortOrder) {
    Integer page = ObjectUtils.defaultIfNull(pageNumber, 0);
    Integer size = ObjectUtils.defaultIfNull(pageSize, Integer.MAX_VALUE);
    boolean sortQuery = false;
    String sortingField = "createdAt";
    // We can only modify the query for the fields that exist in NotificationContent
    if (StringUtils.isNotBlank(sortField) && "createdAt".equalsIgnoreCase(sortField)
            || "provider".equalsIgnoreCase(sortField)
            || "providerCreationTime".equalsIgnoreCase(sortField)
            || "notificationType".equalsIgnoreCase(sortField)
            || "content".equalsIgnoreCase(sortField)) {
        sortingField = sortField;
        sortQuery = true;
    }
    Sort.Order sortingOrder = Sort.Order.desc(sortingField);
    if (StringUtils.isNotBlank(sortOrder) && sortQuery && Sort.Direction.ASC.name().equalsIgnoreCase(sortOrder)) {
        sortingOrder = Sort.Order.asc(sortingField);
    }
    return PageRequest.of(page, size, Sort.by(sortingOrder));
}
 
Example #10
Source File: DictServiceImpl.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
@Override
@Cacheable(key = "'page_dict_' + #p0.currentPage + '_' + #p0.pageSize + '_' + #p1.type + '_' + #p1.label")
public PageBean<Dict> findAll(PageParams pageParams, Dict dict) {
	QDict qDict = QDict.dict;
	// 用户名查询条件
	Predicate qLabelPredicate = null;
	Predicate qTypePredicate = null;
	if (null != dict) {
		if (StringHelper.isNotBlank(dict.getLabel())) {
			qLabelPredicate = qDict.label.like("%" + dict.getLabel().trim() + "%");
		}
		if (StringHelper.isNotBlank(dict.getType())) {
			qTypePredicate = qDict.type.like("%" + dict.getType().trim() + "%");
		}
	}

	Predicate predicate = qDict.id.goe(0).and(qTypePredicate).and(qLabelPredicate);

	Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "id"));
	PageRequest pageRequest = PageUtils.of(pageParams, sort);
	Page<Dict> pageList = dictRepository.findAll(predicate, pageRequest);
	return PageUtils.of(pageList);
}
 
Example #11
Source File: ShowcaseControllerTest.java    From market with MIT License 6 votes vote down vote up
@Test
public void getRegionProducts_SortedByAge_PageSize4() throws Exception {
	String sortBy = "age";
	PageRequest request = PageRequest.of(0, 4, Sort.by(Sort.Direction.ASC, sortBy));
	Page<Product> page = new PageImpl<>(
		Arrays.asList(product11, product12, product13, product14),
		request,
		productsRegion1.size());

	given(productService.findByRegion(any(Region.class), pageableCaptor.capture()))
		.willReturn(page);

	mockMvc.perform(
		get("/regions/{regionId}", region1.getId())
			.param("sort", sortBy)
			.param("size", Integer.toString(request.getPageSize())))
		.andExpect(status().isOk())
		.andExpect(view().name("regions"))
		.andExpect(model().attribute("selectedRegion", equalTo(regionDtoAssembler.toModel(region1))))
		.andExpect(model().attribute("regions", contains(regionDtoAssembler.toDtoArray(totalRegions))))
		.andExpect(model().attribute("distilleries", contains(distilleryDtoAssembler.toDtoArray(distilleriesOfRegion1))))
		.andExpect(model().attribute("page", productAssembler.toModel(page)));
	assertThat(pageableCaptor.getValue(), equalTo(request));
}
 
Example #12
Source File: UserService.java    From SpringAll with MIT License 6 votes vote down vote up
public Page<User> getUserByCondition(int size, int page, User user) {
    Query query = new Query();
    Criteria criteria = new Criteria();

    if (!StringUtils.isEmpty(user.getName())) {
        criteria.and("name").is(user.getName());
    }
    if (!StringUtils.isEmpty(user.getDescription())) {
        criteria.and("description").regex(user.getDescription());
    }

    query.addCriteria(criteria);

    Sort sort = new Sort(Sort.Direction.DESC, "age");
    Pageable pageable = PageRequest.of(page, size, sort);

    List<User> users = template.find(query.with(pageable), User.class);
    return PageableExecutionUtils.getPage(users, pageable, () -> template.count(query, User.class));
}
 
Example #13
Source File: DataInitializer.java    From spring-reactive-sample with GNU General Public License v3.0 6 votes vote down vote up
@EventListener(value = ContextRefreshedEvent.class)
public void init() {
    log.info("start data initialization  ...");
    this.databaseClient.insert()
        .into("posts")
        //.nullValue("id", Integer.class)
        .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("posts")
                .orderBy(Sort.by(desc("id")))
                .as(Post.class)
                .fetch()
                .all()
                .log()
        )
        .subscribe(null, null, () -> log.info("initialization is done..."));
}
 
Example #14
Source File: ActionStatusMsgBeanQuery.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Parametric Constructor.
 *
 * @param definition
 *            QueryDefinition contains the query properties.
 * @param queryConfig
 *            Implementation specific configuration.
 * @param sortPropertyIds
 *            The properties participating in sort.
 * @param sortStates
 *            The ascending or descending state of sort properties.
 */
public ActionStatusMsgBeanQuery(final QueryDefinition definition, final Map<String, Object> queryConfig,
        final Object[] sortPropertyIds, final boolean[] sortStates) {
    super(definition, queryConfig, sortPropertyIds, sortStates);

    if (isNotNullOrEmpty(queryConfig)) {
        currentSelectedActionStatusId = (Long) queryConfig.get(SPUIDefinitions.MESSAGES_BY_ACTIONSTATUS);
        noMessageText = (String) queryConfig.get(SPUIDefinitions.NO_MSG_PROXY);
    }

    if (sortStates != null && sortStates.length > 0) {
        // Initialize sort
        sort = new Sort(sortStates[0] ? Direction.ASC : Direction.DESC, (String) sortPropertyIds[0]);
        // Add sort
        for (int distId = 1; distId < sortPropertyIds.length; distId++) {
            sort.and(new Sort(sortStates[distId] ? Direction.ASC : Direction.DESC,
                    (String) sortPropertyIds[distId]));
        }
    }
}
 
Example #15
Source File: EventController.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "getContractEventInfo",
        notes = "get registered contract event info by page")
@GetMapping(value = {"contractEvent/list/{groupId}/{pageNumber}/{pageSize}",
        "contractEvent/list/{groupId}"})
public BasePageResponse getContractEventInfo(@PathVariable("groupId") Integer groupId,
                                             @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                                             @PathVariable(value = "pageSize", required = false) Integer pageSize) {
    log.debug("start getContractEventInfo.");
    List<ContractEventInfo> resList;
    if (pageNumber == null || pageSize == null) {
        resList = eventService.getContractEventInfoList(groupId);
    } else {
        if (pageNumber < 1) {
            return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0);
        }
        Pageable pageable = new PageRequest(pageNumber - 1, pageSize,
                new Sort(Sort.Direction.DESC, "createTime"));
        resList = eventService.getContractEventInfoList(groupId, pageable);
    }
    log.debug("end getContractEventInfo resList count. {}", resList.size());
    return new BasePageResponse(ConstantCode.RET_SUCCESS, resList, resList.size());
}
 
Example #16
Source File: PageableSpringEncoder.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
private void applySort(RequestTemplate template, Sort sort) {
	Collection<String> existingSorts = template.queries().get("sort");
	List<String> sortQueries = existingSorts != null ? new ArrayList<>(existingSorts)
			: new ArrayList<>();
	if (!sortParameter.equals("sort")) {
		existingSorts = template.queries().get(sortParameter);
		if (existingSorts != null) {
			sortQueries.addAll(existingSorts);
		}
	}
	for (Sort.Order order : sort) {
		sortQueries.add(order.getProperty() + "," + order.getDirection());
	}
	if (!sortQueries.isEmpty()) {
		template.query(sortParameter, sortQueries);
	}
}
 
Example #17
Source File: RepositoryIT.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Test
void findAllByExampleWithSort(@Autowired PersonRepository repository) {

	Example<PersonWithAllConstructor> example = Example.of(personExample(TEST_PERSON_SAMEVALUE));
	List<PersonWithAllConstructor> persons = repository.findAll(example, Sort.by(Sort.Direction.DESC, "name"));

	assertThat(persons).containsExactly(person2, person1);
}
 
Example #18
Source File: PermissionController.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@RequiresPermissions("ueboot:permission:read")
@RequestMapping(value = "/page", method = RequestMethod.POST)
public Response<Page<PermissionResp>> page(@PageableDefault(value = 15, sort = {"id"}, direction = Sort.Direction.DESC)
                                                   Pageable pageable, @RequestBody(required = false) PermissionFindReq req) {
    Page<Permission> entities = permissionService.findBy(pageable);
    Page<PermissionResp> body = entities.map(entity -> {
        PermissionResp resp = new PermissionResp();
        BeanUtils.copyProperties(entity, resp);
        return resp;
    });

    return new Response<>(body);
}
 
Example #19
Source File: PageVoWithSort.java    From spring-cloud-yes with Apache License 2.0 5 votes vote down vote up
public Sort getSpringSort() {
    if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
        return new Sort(
                new Sort.Order(
                        this.getSpringDirection(),
                        this.sort
                )
        );
    }
    return null;
}
 
Example #20
Source File: KeyStoreService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * get local user KeyStores with privateKey
 * without external user
 */
public List<KeyStoreInfo> getLocalKeyStoreList() {
    Sort sort = new Sort(Sort.Direction.ASC, "userName");
    List<KeyStoreInfo> keyStores = keystoreRepository.findAll(
            (Root<KeyStoreInfo> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) -> {
                Predicate predicate = criteriaBuilder.equal(root.get("type"), KeyTypes.LOCALUSER.getValue());
                return criteriaBuilder.and(predicate);
            }, sort);
    // return local KeyStore with decrypted privateKey
    keyStores.forEach(info -> {
        String realPrivateKey = aesUtils.aesDecrypt(info.getPrivateKey());
        info.setPrivateKey(realPrivateKey);
    });
    return keyStores;
}
 
Example #21
Source File: DatastoreIntegrationTests.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Test
public void testSliceSort() {
	List<TestEntity> results = this.testEntityRepository.findEntitiesWithCustomQuerySort(Sort.by("color"));

	assertThat(results.get(0)).isEqualTo(this.testEntityB);
	assertThat(results).containsExactlyInAnyOrder(this.testEntityA, this.testEntityB, this.testEntityC,
			this.testEntityD);
}
 
Example #22
Source File: BaseService.java    From flash-waimai with MIT License 5 votes vote down vote up
@Override
public List<T> queryAll(List<SearchFilter> filters, Sort sort) {
    Specification<T> specification = DynamicSpecifications.bySearchFilter(filters,dao.getDataClass());
    if(sort==null){
        return dao.findAll(specification);
    }
    return dao.findAll(specification,sort);
}
 
Example #23
Source File: PostsController.java    From blog-spring with MIT License 5 votes vote down vote up
@GetMapping("/drafts")
public String drafts(HttpServletRequest request, Model model, Pageable pageable) {
  pageable =
      PageRequest.of(
          pageable.getPageNumber(), pageable.getPageSize(), new Sort(Sort.Direction.DESC, "id"));

  Page<Post> postPage = postService.findDrafts(pageable);

  model.addAttribute("postPage", postPage);
  PaginationHelper.setPageLink(model, request);
  return "admin/posts/drafts";
}
 
Example #24
Source File: ContentServiceImpl.java    From hermes with Apache License 2.0 5 votes vote down vote up
/**
 * 内容管理查询结果
 * 
 * @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 #25
Source File: PostsController.java    From blog-spring with MIT License 5 votes vote down vote up
@GetMapping("")
public String index(HttpServletRequest request, Model model, Pageable pageable) {
  pageable =
      PageRequest.of(
          pageable.getPageNumber(), pageable.getPageSize(), new Sort(Sort.Direction.DESC, "id"));

  Page<Post> postPage = postService.findNormalPosts(pageable);

  model.addAttribute("postPage", postPage);
  PaginationHelper.setPageLink(model, request);
  return "admin/posts/index";
}
 
Example #26
Source File: SessionServiceImpl.java    From sctalk with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public long addSession(long userId, long peerId, int type) {
    int time = CommonUtils.currentTimeSeconds();

    // 查询已有数据
    SearchCriteria<IMRecentSession> recentSessionCriteria = new SearchCriteria<>();
    recentSessionCriteria.add(JpaRestrictions.eq("userId", userId, false));
    recentSessionCriteria.add(JpaRestrictions.eq("peerId", peerId, false));
    recentSessionCriteria.add(JpaRestrictions.eq("type", type, false));

    List<IMRecentSession> recentSessions =
            recentSessionRepository.findAll(recentSessionCriteria, new Sort(Sort.Direction.DESC, "updated"));

    IMRecentSession recentSession;
    if (!recentSessions.isEmpty()) {
        recentSession = recentSessions.get(0);
        recentSession.setStatus(DBConstant.DELETE_STATUS_OK);
        recentSession.setUpdated(time);
    } else {

        byte sesstionType = (byte) type;
        recentSession = new IMRecentSession();
        recentSession.setUserId(userId);
        recentSession.setPeerId(peerId);
        recentSession.setType(sesstionType);
        recentSession.setStatus(DBConstant.DELETE_STATUS_OK);
        recentSession.setCreated(time);
        recentSession.setUpdated(time);
    }

    recentSession = recentSessionRepository.save(recentSession);

    return recentSession.getId();
}
 
Example #27
Source File: PagingUtility.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
static Sort sanitizeRolloutSortParam(final String sortParam) {
    if (sortParam == null) {
        // default
        return new Sort(Direction.ASC, RolloutFields.ID.getFieldName());
    }
    return new Sort(SortUtility.parse(RolloutFields.class, sortParam));
}
 
Example #28
Source File: AbstractCrudService.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * List all by sort
 *
 * @param sort sort
 * @return List
 */
@Override
public List<DOMAIN> listAll(Sort sort) {
    Assert.notNull(sort, "Sort info must not be null");

    return repository.findAll(sort);
}
 
Example #29
Source File: SysHelpService.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 根据分类分页查询
 * @param pageNo
 * @param pageSize
 * @param cate
 * @return
 */
public Page<SysHelp> findByCondition(int pageNo,int pageSize,SysHelpClassification cate){
    Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "sort"));
    Pageable pageable = new PageRequest(pageNo - 1, pageSize, sort);
    Specification specification = new Specification() {
        List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();

        @Override
        public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
            predicates.add(criteriaBuilder.equal(root.get("sysHelpClassification"),cate));
            return criteriaBuilder.and(predicates.toArray(new javax.persistence.criteria.Predicate[predicates.size()]));
        }
    };
    return sysHelpDao.findAll(specification,pageable);
}
 
Example #30
Source File: LinqImpl.java    From linq with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Page<T> paging(Pageable pageable) {
	if (parent != null) {
		applyPredicateToCriteria(sq);
		return parent.paging(pageable);
	}
	List<T> list;
	if (pageable == null) {
		list = list();
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		if (sort != null) {
			orders.addAll(QueryUtils.toOrders(sort, root, cb));
		}
		applyPredicateToCriteria(criteria);
		TypedQuery<?> query = em.createQuery(criteria);
		Long offset = pageable.getOffset();
		query.setFirstResult(offset.intValue());
		query.setMaxResults(pageable.getPageSize());

		Long total = JpaUtil.count(criteria);
		List<T> content = Collections.<T> emptyList();
		if (total > pageable.getOffset()) {
			content = transform(query, false);
		}

		return new PageImpl<T>(content, pageable, total);
	}
}