org.springframework.data.jpa.domain.Specification Java Examples
The following examples show how to use
org.springframework.data.jpa.domain.Specification.
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: GreatEqualTest.java From jpa-spec with MIT License | 7 votes |
@Test public void should_be_able_to_find_by_using_great_equal() { // given Person jack = new PersonBuilder() .name("Jack") .age(20) .build(); Person eric = new PersonBuilder() .name("Eric") .age(18) .build(); personRepository.save(jack); personRepository.save(eric); // when Specification<Person> specification = Specifications.<Person>and() .ge("age", 20) .build(); List<Person> persons = personRepository.findAll(specification); // then assertThat(persons.size()).isEqualTo(1); }
Example #2
Source File: SpecificationArgumentResolverTest.java From specification-arg-resolver with Apache License 2.0 | 6 votes |
@Test public void resolvesJoinContainerWithRegularJoin() throws Exception { MethodParameter param = MethodParameter.forExecutable(testMethod("testMethod_joinContainerWithRegularJoin"), 0); FakeWebRequest req = new FakeWebRequest(); QueryContext queryCtx = new WebRequestQueryContext(req); req.setParameterValues("path1", "value1"); Specification<?> resolved = (Specification<?>) resolver.resolveArgument(param, null, req, null); assertThat(innerSpecs(resolved)) .hasSize(2) .contains(new Like<Object>(queryCtx, "path1", new String[] { "value1" })) .contains(new Conjunction<Object>( new net.kaczmarzyk.spring.data.jpa.domain.Join<Object>(queryCtx, "join1", "alias1", JoinType.INNER, true), new net.kaczmarzyk.spring.data.jpa.domain.Join<Object>(queryCtx, "join2", "alias2", JoinType.LEFT, false))); }
Example #3
Source File: GenericJpaRepositoryImpl.java From genericdao with Artistic License 2.0 | 6 votes |
protected <S> Root<T> applySpecificationToCriteria(Specification<T> spec, CriteriaQuery<S> query) { Assert.notNull(query); Root<T> root = query.from(getDomainClass()); if (spec == null) { return root; } CriteriaBuilder builder = entityManager.getCriteriaBuilder(); Predicate predicate = spec.toPredicate(root, query, builder); if (predicate != null) { query.where(predicate); } return root; }
Example #4
Source File: DisjunctionSpecificationResolver.java From specification-arg-resolver with Apache License 2.0 | 6 votes |
public Specification<Object> buildSpecification(WebRequestProcessingContext context, Disjunction def) { List<Specification<Object>> innerSpecs = new ArrayList<Specification<Object>>(); for (And innerAndDef : def.value()) { Specification<Object> innerAnd = andResolver.buildSpecification(context, innerAndDef); if (innerAnd != null) { innerSpecs.add(innerAnd); } } for (Spec innerDef : def.or()) { Specification<Object> innerSpec = specResolver.buildSpecification(context, innerDef); if (innerSpec != null) { innerSpecs.add(innerSpec); } } return innerSpecs.isEmpty() ? null : new net.kaczmarzyk.spring.data.jpa.domain.Disjunction<>(innerSpecs); }
Example #5
Source File: SimpleBaseRepository.java From es with Apache License 2.0 | 6 votes |
/** * Applies the given {@link org.springframework.data.jpa.domain.Specification} to the given {@link javax.persistence.criteria.CriteriaQuery}. * * @param spec can be {@literal null}. * @param query must not be {@literal null}. * @return */ private <S> Root<M> applySpecificationToCriteria(Specification<M> spec, CriteriaQuery<S> query) { Assert.notNull(query); Root<M> root = query.from(entityClass); if (spec == null) { return root; } CriteriaBuilder builder = em.getCriteriaBuilder(); Predicate predicate = spec.toPredicate(root, query, builder); if (predicate != null) { query.where(predicate); } return root; }
Example #6
Source File: ReplyServiceImpl.java From JavaQuarkBBS with Apache License 2.0 | 6 votes |
@Override public Page<Reply> getReplyByPage(Integer postsId, int pageNo, int length) { Sort.Order order = new Sort.Order(Sort.Direction.ASC, "id"); Sort sort = new Sort(order); PageRequest pageable = new PageRequest(pageNo, length, sort); Specification<Reply> specification = new Specification<Reply>() { @Override public Predicate toPredicate(Root<Reply> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { Path<Integer> $posts = root.get("posts"); Predicate predicate = criteriaBuilder.and(criteriaBuilder.equal($posts, postsId)); return predicate; } }; Page<Reply> page = repository.findAll(specification, pageable); return page; }
Example #7
Source File: SpecificationArgumentResolverTest.java From specification-arg-resolver with Apache License 2.0 | 6 votes |
@Test public void resolvesJoinContainerWithJoinFetch() throws Exception { MethodParameter param = MethodParameter.forExecutable(testMethod("testMethod_joinContainerWithJoinFetch"), 0); NativeWebRequest req = mock(NativeWebRequest.class); QueryContext queryCtx = new WebRequestQueryContext(req); when(req.getParameterValues("path1")).thenReturn(new String[] { "value1" }); Specification<?> resolved = (Specification<?>) resolver.resolveArgument(param, null, req, null); assertThat(innerSpecs(resolved)) .hasSize(2) .contains(new Like<Object>(queryCtx, "path1", new String[] { "value1" })) .contains(new Conjunction<Object>( new net.kaczmarzyk.spring.data.jpa.domain.JoinFetch<Object>(new String[] { "fetch1" }, JoinType.LEFT), new net.kaczmarzyk.spring.data.jpa.domain.JoinFetch<Object>(new String[] { "fetch2" }, JoinType.INNER))); }
Example #8
Source File: JpaBaseEventDao.java From Groza with Apache License 2.0 | 6 votes |
private Specification<EventEntity> getEntityFieldsSpec(UUID tenantId, EntityId entityId, String eventType) { return (root, criteriaQuery, criteriaBuilder) -> { List<Predicate> predicates = new ArrayList<>(); if (tenantId != null) { Predicate tenantIdPredicate = criteriaBuilder.equal(root.get("tenantId"), UUIDConverter.fromTimeUUID(tenantId)); predicates.add(tenantIdPredicate); } if (entityId != null) { Predicate entityTypePredicate = criteriaBuilder.equal(root.get("entityType"), entityId.getEntityType()); predicates.add(entityTypePredicate); Predicate entityIdPredicate = criteriaBuilder.equal(root.get("entityId"), UUIDConverter.fromTimeUUID(entityId.getId())); predicates.add(entityIdPredicate); } if (eventType != null) { Predicate eventTypePredicate = criteriaBuilder.equal(root.get("eventType"), eventType); predicates.add(eventTypePredicate); } return criteriaBuilder.and(predicates.toArray(new Predicate[]{})); }; }
Example #9
Source File: AuditDao.java From JuniperBot with GNU General Public License v3.0 | 6 votes |
@Transactional public List<AuditActionDto> getActions(long guildId, AuditActionRequest request) { Specification<AuditAction> spec = rootAuditSpec(guildId); if (request != null) { if (request.getActionType() != null) { spec = spec.and(withActionType(request.getActionType())); } if (request.getUserId() != null) { spec = spec.and(withUserId(request.getUserId())); } if (request.getChannelId() != null) { spec = spec.and(withChannelId(request.getChannelId())); } if (request.getOlderThan() != null) { spec = spec.and(withOlderThan(request.getOlderThan())); } if (request.getStartDate() != null) { spec = spec.and(withStartDate(request.getStartDate())); } if (request.getEndDate() != null) { spec = spec.and(withEndDate(request.getEndDate())); } } List<AuditAction> actions = actionRepository.findAll(spec, PageRequest.of(0, 50)).getContent(); return apiMapper.getAuditActionDtos(actions); }
Example #10
Source File: AnnotatedConjunctionSpecInterfaceArgumentResolverTest.java From specification-arg-resolver with Apache License 2.0 | 6 votes |
@Test // TC-1. interface with @Conjunction spec public void createsSpecFromSimpleAnnotatedInterface() throws Exception { MethodParameter param = methodParameter("annotatedInterface", GenderOrLastNameAndRegistrationDateFilter.class); NativeWebRequest req = nativeWebRequest() .withParameterValues("gender", "MALE") .withParameterValues("lastName", "Simpson") .withParameterValues("registrationDate", "2014-03-20").build(); WebRequestProcessingContext ctx = new WebRequestProcessingContext(param, req); Specification<?> resolved = (Specification<?>) specificationArgumentResolver.resolveArgument(param, null, req, null); assertThat(resolved) .isInstanceOf(GenderOrLastNameAndRegistrationDateFilter.class); assertThat(innerSpecs(resolved)) .hasSize(2) .containsExactlyInAnyOrder( new Disjunction<>( new EmptyResultOnTypeMismatch<>(equal(ctx, "gender", "MALE")), new EmptyResultOnTypeMismatch<>(equal(ctx, "lastName", "Simpson")) ), new EmptyResultOnTypeMismatch<>(in(ctx, "registrationDate", "2014-03-20")) ); }
Example #11
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 #12
Source File: SpecTest.java From code with Apache License 2.0 | 6 votes |
/** * 分页查询 */ @Test public void testPage() { Specification<Customer> specification = new Specification<Customer>() { @Override public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.like(root.get("custName").as(String.class), "阿里巴%"); } }; /* * 构造分页参数 * Pageable : 接口 * PageRequest实现了Pageable接口,调用构造方法的形式构造 * 第一个参数:页码(从0开始) * 第二个参数:每页查询条数 * Pageable pageable = new PageRequest(0, 5); */ Pageable pageable = PageRequest.of(0, 5); Page<Customer> page = customerDao.findAll(specification, pageable); System.out.println("总记录数"+page.getTotalElements()); System.out.println("总页数"+page.getTotalPages()); page.getContent().forEach(System.out::println); }
Example #13
Source File: TeamSkillQueryService.java From TeamDojo with Apache License 2.0 | 5 votes |
/** * Return a {@link List} of {@link TeamSkillDTO} which matches the criteria from the database * * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @Transactional(readOnly = true) public List<TeamSkillDTO> findByCriteria(TeamSkillCriteria criteria) { log.debug("find by criteria : {}", criteria); final Specification<TeamSkill> specification = createSpecification(criteria); return teamSkillMapper.toDto(teamSkillRepository.findAll(specification)); }
Example #14
Source File: JobQueryService.java From alchemy with Apache License 2.0 | 5 votes |
/** * Return the number of matching entities in the database. * @param criteria The object which holds all the filters, which the entities should match. * @return the number of matching entities. */ @Transactional(readOnly = true) public long countByCriteria(JobCriteria criteria) { log.debug("count by criteria : {}", criteria); final Specification<Job> specification = createSpecification(criteria); return jobRepository.count(specification); }
Example #15
Source File: NotInE2eTest.java From specification-arg-resolver with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/not-in/customers", params = "registrationDateNotIn") @ResponseBody public Object findCustomersByRegistrationDate( @Spec(path = "registrationDate", params = "registrationDateNotIn", spec = NotIn.class) Specification<Customer> spec) { return customerRepo.findAll(spec); }
Example #16
Source File: JpaTargetFilterQueryManagement.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Override public Page<TargetFilterQuery> findByRsql(final Pageable pageable, final String rsqlFilter) { List<Specification<JpaTargetFilterQuery>> specList = Collections.emptyList(); if (!StringUtils.isEmpty(rsqlFilter)) { specList = Collections.singletonList( RSQLUtility.parse(rsqlFilter, TargetFilterQueryFields.class, virtualPropertyReplacer, database)); } return convertPage(findTargetFilterQueryByCriteriaAPI(pageable, specList), pageable); }
Example #17
Source File: SimpleSpecificationResolverTest.java From specification-arg-resolver with Apache License 2.0 | 5 votes |
@Test public void buildsTheSpecUsingCustomMultiValueWebParametersNames() throws Exception { MethodParameter param = MethodParameter.forExecutable(testMethod("testMethod4"), 0); NativeWebRequest req = mock(NativeWebRequest.class); QueryContext queryCtx = new WebRequestQueryContext(req); when(req.getParameterValues("theParameter")).thenReturn(new String[] { "theValue", "theValue2" }); when(req.getParameterValues("theParameter2")).thenReturn(new String[] { "theValue3", "theValue4" }); WebRequestProcessingContext ctx = new WebRequestProcessingContext(param, req); Specification<?> resolved = resolver.buildSpecification(ctx, param.getParameterAnnotation(Spec.class)); assertThat(resolved).isEqualTo(new EqualEnum<>(queryCtx, "thePath", new String[] { "theValue", "theValue2", "theValue3", "theValue4" })); }
Example #18
Source File: SinkQueryService.java From alchemy with Apache License 2.0 | 5 votes |
/** * Return a {@link Page} of {@link SinkDTO} which matches the criteria from the database. * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. */ @Transactional(readOnly = true) public Page<SinkDTO> findByCriteria(SinkCriteria criteria, Pageable page) { log.debug("find by criteria : {}, page: {}", criteria, page); final Specification<Sink> specification = createSpecification(criteria); return sinkRepository.findAll(specification, page) .map(sinkMapper::toDto); }
Example #19
Source File: NoCountPagingRepository.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Override protected Page<T> readPage(final TypedQuery<T> query, final Pageable pageable, final Specification<T> spec) { query.setFirstResult((int) pageable.getOffset()); query.setMaxResults(pageable.getPageSize()); final List<T> content = query.getResultList(); return new PageImpl<>(content, pageable, content.size()); }
Example #20
Source File: QcTask.java From youkefu with Apache License 2.0 | 5 votes |
@Scheduled(fixedDelay= 3000 , initialDelay = 20000) public void checkVoiceTrans() { if(UKDataContext.model.get("qc") != null) { Page<StatusEvent> transList = null ; { transList = statusEventRes.findAll(new Specification<StatusEvent>(){ @Override public Predicate toPredicate(Root<StatusEvent> root, CriteriaQuery<?> query, CriteriaBuilder cb) { List<Predicate> list = new ArrayList<Predicate>(); list.add(cb.equal(root.get("transtatus").as(String.class),UKDataContext.TransStatus.INTRANS.toString())) ; Predicate[] p = new Predicate[list.size()]; return cb.and(list.toArray(p)); }}, new PageRequest(0, 100, Sort.Direction.ASC, "transbegin")) ; if(transList.getContent().size()>0) { List<StatusEvent> needUpdateList = new ArrayList<StatusEvent>(); for(StatusEvent statusEvent : transList.getContent()) { QualityConfig qConfig = UKTools.initQualityConfig(statusEvent.getOrgi()) ; if(qConfig!=null && qConfig.isPhonetic() && !StringUtils.isBlank(qConfig.getEngine())) { PhoneticTranscription trans = (PhoneticTranscription) UKDataContext.getContext().getBean(qConfig.getEngine()) ; if(trans!=null) { if(!StringUtils.isBlank(statusEvent.getTranid())) {//根据转写引擎返回的任务ID去查询,实时转写状态 boolean needUpdata = trans.getStatus(statusEvent, qConfig) ; if(needUpdata) { needUpdateList.add(statusEvent) ; } } } } } if(needUpdateList.size() > 0) { statusEventRes.save(needUpdateList) ; } } } ; } }
Example #21
Source File: SpecificationArgumentResolver.java From specification-arg-resolver with Apache License 2.0 | 5 votes |
private void resolveSpecFromParameterAnnotations(WebRequestProcessingContext context, List<Specification<Object>> accum) { forEachSupportedSpecificationDefinition( context.getParameterAnnotations(), specDefinition -> { Specification<Object> specification = buildSpecification(context, specDefinition); if (nonNull(specification)) { accum.add(specification); } } ); }
Example #22
Source File: InTest.java From jpa-spec with MIT License | 5 votes |
@Test public void should_be_able_to_find_by_using_in() { // given Person jack = new PersonBuilder() .name("Jack") .nickName("Jack") .age(18) .build(); Person eric = new PersonBuilder() .name("Eric") .nickName("Eric") .age(20) .build(); personRepository.save(jack); personRepository.save(eric); // when Specification<Person> specification = Specifications.<Person>and() .in(isNotBlank(jack.getName()), "name", Arrays.asList("Jack", "Eric")) .in("name", Arrays.asList("Jack", "Eric")) .build(); List<Person> persons = personRepository.findAll(specification); // then assertThat(persons.size()).isEqualTo(2); }
Example #23
Source File: DistributionSetSpecification.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
/** * {@link Specification} for retrieving {@link DistributionSet}s by tag. * * @param tagId * the ID of the distribution set which must be assigned * @return the {@link DistributionSet} {@link Specification} */ public static Specification<JpaDistributionSet> hasTag(final Long tagId) { return (targetRoot, query, cb) -> { final SetJoin<JpaDistributionSet, JpaDistributionSetTag> tags = targetRoot.join(JpaDistributionSet_.tags, JoinType.LEFT); return cb.equal(tags.get(JpaDistributionSetTag_.id), tagId); }; }
Example #24
Source File: BaseService.java From flash-waimai with MIT License | 5 votes |
@Override public Page<T> queryPage(Page<T> page) { Pageable pageable = null; if(page.getSort()!=null) { pageable = PageRequest.of(page.getCurrent()-1, page.getSize(), page.getSort()); }else{ pageable = PageRequest.of(page.getCurrent()-1,page.getSize(), Sort.Direction.DESC,"id"); } Specification<T> specification = DynamicSpecifications.bySearchFilter(page.getFilters(),dao.getDataClass()); org.springframework.data.domain.Page<T> pageResult = dao.findAll(specification,pageable); page.setTotal(Integer.valueOf(pageResult.getTotalElements()+"")); page.setRecords(pageResult.getContent()); return page; }
Example #25
Source File: CategorySpecifications.java From wallride with Apache License 2.0 | 5 votes |
public static Specification<Category> hasArticles(String language) { return (root, query, cb) -> { query.distinct(true); Subquery<Long> subquery = query.subquery(Long.class); Root<Article> a = subquery.from(Article.class); Join<Article, Category> c = a.join(Article_.categories, JoinType.INNER); subquery.select(c.get(Category_.id)).where(cb.equal(a.get(Article_.status), Article.Status.PUBLISHED)); List<Predicate> predicates = new ArrayList<>(); predicates.add(root.get(Category_.id).in(subquery)); predicates.add(cb.equal(root.get(Category_.language), language)); return cb.and(predicates.toArray(new Predicate[0])); }; }
Example #26
Source File: FieldQueryService.java From alchemy with Apache License 2.0 | 5 votes |
/** * Return a {@link List} of {@link FieldDTO} which matches the criteria from the database. * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @Transactional(readOnly = true) public List<FieldDTO> findByCriteria(FieldCriteria criteria) { log.debug("find by criteria : {}", criteria); final Specification<Field> specification = createSpecification(criteria); return fieldMapper.toDto(fieldRepository.findAll(specification)); }
Example #27
Source File: TagSpecification.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
/** * {@link Specification} for retrieving {@link DistributionSetTag}s by * assigned {@link DistributionSet}. * * @param dsId * of the distribution set * * @return the {@link JpaDistributionSetTag} {@link Specification} */ public static Specification<JpaDistributionSetTag> ofDistributionSet(final Long dsId) { return (dsRoot, query, criteriaBuilder) -> { final Join<JpaDistributionSetTag, JpaDistributionSet> tagJoin = dsRoot .join(JpaDistributionSetTag_.assignedToDistributionSet); query.distinct(true); return criteriaBuilder.equal(tagJoin.get(JpaDistributionSet_.id), dsId); }; }
Example #28
Source File: JpaSpecs.java From spring4-sandbox with Apache License 2.0 | 5 votes |
public static Specification<Conference> upcomingConferences() { return new Specification<Conference>() { @Override public Predicate toPredicate(Root<Conference> root, CriteriaQuery<?> query, CriteriaBuilder cb) { return cb.greaterThan(root.get("startedDate").as(Date.class), cb.currentTimestamp()); } }; }
Example #29
Source File: SimpleSpecificationResolverTest.java From specification-arg-resolver with Apache License 2.0 | 5 votes |
@Test public void returnsNullIfTheWebParameterIsMissing_defaultParameterName() throws Exception { MethodParameter param = MethodParameter.forExecutable(testMethod("testMethod1"), 0); NativeWebRequest req = mock(NativeWebRequest.class); WebRequestProcessingContext ctx = new WebRequestProcessingContext(param, req); Specification<?> resolved = resolver.buildSpecification(ctx, param.getParameterAnnotation(Spec.class)); assertThat(resolved).isNull(); }
Example #30
Source File: AclJpaQuery.java From strategy-spring-security-acl with Apache License 2.0 | 5 votes |
private void installAclSpec(Specification<Object> aclJpaSpec) { // force rerender by resetting alias root.alias(null); // build acl predicate Predicate aclPredicate = aclJpaSpec.toPredicate(root, cachedCriteriaQuery, em.getCriteriaBuilder()); // install acl predicate aclPredicateTargetSource.installAcl(aclPredicate); logger.debug("ACL Jpa Specification installed for method '{}' and query {}: {}", method, query, aclJpaSpec); }