Search in sources :

Example 1 with Specification

use of org.springframework.data.jpa.domain.Specification in project CzechIdMng by bcvsolutions.

the class DefaultFormServiceItegrationTest method findOwnerByCriteria.

@Test
public void findOwnerByCriteria() {
    IdmRoleDto owner = helper.createRole();
    IdmRoleDto ownerTwo = helper.createRole();
    IdmFormDefinitionDto formDefinition = formService.getDefinition(IdmRole.class);
    IdmFormAttributeDto attribute = formDefinition.getFormAttributes().get(0);
    // 
    formService.saveValues(owner.getId(), IdmRole.class, attribute, Lists.newArrayList("test"));
    formService.saveValues(ownerTwo.getId(), IdmRole.class, attribute, Lists.newArrayList("test2"));
    Specification<IdmRole> criteria = new Specification<IdmRole>() {

        public Predicate toPredicate(Root<IdmRole> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            Subquery<IdmRoleFormValue> subquery = query.subquery(IdmRoleFormValue.class);
            Root<IdmRoleFormValue> subRoot = subquery.from(IdmRoleFormValue.class);
            subquery.select(subRoot);
            Predicate predicate = builder.and(builder.equal(subRoot.get(IdmRoleFormValue_.owner), root), builder.equal(subRoot.get(IdmRoleFormValue_.formAttribute).get(IdmFormAttribute_.id), attribute.getId()), builder.equal(subRoot.get(IdmRoleFormValue_.stringValue), "test"));
            subquery.where(predicate);
            // 
            return query.where(builder.exists(subquery)).getRestriction();
        }
    };
    List<IdmRole> roles = roleRepository.findAll(criteria, (Pageable) null).getContent();
    assertEquals(1, roles.size());
    assertEquals(owner.getId(), roles.get(0).getId());
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) IdmRoleDto(eu.bcvsolutions.idm.core.api.dto.IdmRoleDto) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) Specification(org.springframework.data.jpa.domain.Specification) Predicate(javax.persistence.criteria.Predicate) Pageable(org.springframework.data.domain.Pageable) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) IdmRole(eu.bcvsolutions.idm.core.model.entity.IdmRole) IdmRoleFormValue(eu.bcvsolutions.idm.core.model.entity.eav.IdmRoleFormValue) AbstractIntegrationTest(eu.bcvsolutions.idm.test.api.AbstractIntegrationTest) Test(org.junit.Test)

Example 2 with Specification

use of org.springframework.data.jpa.domain.Specification in project FP-PSP-SERVER by FundacionParaguaya.

the class SnapshotEconomicSpecification method createdAtBetween2Dates.

public static Specification<SnapshotEconomicEntity> createdAtBetween2Dates(String dateFrom, String dateTo) {
    return new Specification<SnapshotEconomicEntity>() {

        @Override
        public Predicate toPredicate(Root<SnapshotEconomicEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<>();
            if (dateFrom != null && dateTo != null) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(SHORT_DATE_FORMAT);
                predicates.add(cb.greaterThanOrEqualTo(root.get(SnapshotEconomicEntity_.getCreatedAt()), LocalDate.parse(dateFrom, formatter).atStartOfDay()));
                predicates.add(cb.lessThan(root.get(SnapshotEconomicEntity_.getCreatedAt()), LocalDate.parse(dateTo, formatter).plusDays(1).atStartOfDay()));
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) ArrayList(java.util.ArrayList) Specification(org.springframework.data.jpa.domain.Specification) DateTimeFormatter(java.time.format.DateTimeFormatter) Predicate(javax.persistence.criteria.Predicate)

Example 3 with Specification

use of org.springframework.data.jpa.domain.Specification in project FP-PSP-SERVER by FundacionParaguaya.

the class FamilySpecification method createdAtBetween2Dates.

public static Specification<FamilyEntity> createdAtBetween2Dates(String dateFrom, String dateTo) {
    return new Specification<FamilyEntity>() {

        @Override
        public Predicate toPredicate(Root<FamilyEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> predicates = new ArrayList<>();
            if (dateFrom != null && dateTo != null) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(SHORT_DATE_FORMAT);
                Subquery<SnapshotEconomicEntity> subquery = query.subquery(SnapshotEconomicEntity.class);
                Root<SnapshotEconomicEntity> fromSnapshot = subquery.from(SnapshotEconomicEntity.class);
                subquery.select(fromSnapshot.get(SnapshotEconomicEntity_.getFamily()).get(ID_FAMILY));
                predicates.add(cb.greaterThanOrEqualTo(fromSnapshot.get(SnapshotEconomicEntity_.getCreatedAt()), LocalDate.parse(dateFrom, formatter).atStartOfDay()));
                predicates.add(cb.lessThan(fromSnapshot.get(SnapshotEconomicEntity_.getCreatedAt()), LocalDate.parse(dateTo, formatter).plusDays(1).atStartOfDay()));
                subquery.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
                return cb.in(root.get(ID_FAMILY)).value(subquery);
            }
            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    };
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Root(javax.persistence.criteria.Root) SnapshotEconomicEntity(py.org.fundacionparaguaya.pspserver.surveys.entities.SnapshotEconomicEntity) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) ArrayList(java.util.ArrayList) Specification(org.springframework.data.jpa.domain.Specification) DateTimeFormatter(java.time.format.DateTimeFormatter) Predicate(javax.persistence.criteria.Predicate)

Example 4 with Specification

use of org.springframework.data.jpa.domain.Specification in project tutorials by eugenp.

the class JPASpecificationIntegrationTest method givenFirstOrLastNameAndAgeGenericBuilder_whenGettingListOfUsers_thenCorrect.

@Test
public void givenFirstOrLastNameAndAgeGenericBuilder_whenGettingListOfUsers_thenCorrect() {
    GenericSpecificationsBuilder<User> builder = new GenericSpecificationsBuilder<>();
    Function<SpecSearchCriteria, Specification<User>> converter = UserSpecification::new;
    CriteriaParser parser = new CriteriaParser();
    List<User> results = repository.findAll(builder.build(parser.parse("( lastName:doe OR firstName:john ) AND age:22"), converter));
    assertThat(results, hasSize(1));
    assertThat(userJohn, isIn(results));
    assertThat(userTom, not(isIn(results)));
}
Also used : User(org.baeldung.persistence.model.User) CriteriaParser(org.baeldung.web.util.CriteriaParser) GenericSpecificationsBuilder(org.baeldung.persistence.dao.GenericSpecificationsBuilder) UserSpecification(org.baeldung.persistence.dao.UserSpecification) Specification(org.springframework.data.jpa.domain.Specification) SpecSearchCriteria(org.baeldung.web.util.SpecSearchCriteria) Test(org.junit.Test)

Example 5 with Specification

use of org.springframework.data.jpa.domain.Specification in project tutorials-java by Artister.

the class ApplicationTests method specificationTest.

/**
 * 1) 分页
 * 2) 排序
 * 3) 条件: age > 50
 */
@Test
public void specificationTest() {
    Sort.Order order = new Sort.Order(Sort.Direction.ASC, "id");
    Sort sort = new Sort(order);
    Specification<User> specification = new Specification<User>() {

        /**
         * @param root  查询的类型-User
         * @param criteriaQuery 添加查询条件
         * @param criteriaBuilder 构建Predicate
         * @return
         */
        @Override
        public Predicate toPredicate(// 查询的实体类-根对象
        Root<User> root, // 查询的语句
        CriteriaQuery<?> criteriaQuery, // 
        CriteriaBuilder criteriaBuilder) {
            // root (User (age))--->从root到age就是这个path
            Path path = root.get("age");
            // 就是条件
            return criteriaBuilder.gt(path, 50);
        }
    };
    Pageable pageable = new PageRequest(0, 5, sort);
    Page<User> Users = jpaRepository.findAll(specification, pageable);
    out.println("总页数" + Users.getTotalPages());
    out.println("总记录数" + Users.getTotalElements());
    out.println("当前第几页" + Users.getNumber() + 1);
    out.println("当前页面的集合" + Users.getContent());
    out.println("当前页面的记录数" + Users.getNumberOfElements());
}
Also used : User(org.ko.web.domain.User) Specification(org.springframework.data.jpa.domain.Specification) PageRequest(org.springframework.data.domain.PageRequest) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) Test(org.junit.Test)

Aggregations

Specification (org.springframework.data.jpa.domain.Specification)17 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)12 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)12 Root (javax.persistence.criteria.Root)12 Predicate (javax.persistence.criteria.Predicate)10 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)4 Charge (com.code.server.db.model.Charge)3 LocalDateTime (java.time.LocalDateTime)3 Sort (org.springframework.data.domain.Sort)3 IdmRoleDto (eu.bcvsolutions.idm.core.api.dto.IdmRoleDto)2 IdmFormAttributeDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto)2 IdmFormDefinitionDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto)2 IdmRole (eu.bcvsolutions.idm.core.model.entity.IdmRole)2 IdmRoleFormValue (eu.bcvsolutions.idm.core.model.entity.eav.IdmRoleFormValue)2 BasePermission (eu.bcvsolutions.idm.core.security.api.domain.BasePermission)2 AuthorizableType (eu.bcvsolutions.idm.core.security.api.dto.AuthorizableType)2 AuthorizableService (eu.bcvsolutions.idm.core.security.api.service.AuthorizableService)2 AbstractIntegrationTest (eu.bcvsolutions.idm.test.api.AbstractIntegrationTest)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2