Spring-Data-JPA with QueryDslPredicateExecutor and Joining into a collection

前端 未结 2 1697
南旧
南旧 2021-02-01 07:29

Let\'s say I have a data model like this (pseudocode):

@Entity
Person {
    @OneToMany
    List attributes;
}

@Entity
PersonAttribute {
          


        
2条回答
  •  走了就别回头了
    2021-02-01 08:11

    You can't directly join a column in a predicate but you can create an any() expressions like this

    QPerson.person.attributes.any().attributeValue.eq("X")
    

    This approach has the restriction that the join expression QPerson.person.attributes.any() can be used in only one filter. It has though the benefit that this expression is internally converted into a subquery which doesn't conflict with paging.

    For multiple restrictions you will need to construct a subquery expression explicitly like this

    QPersonAttribute attribute = QPersonAttribute.personAttribute;
    new JPASubQuery().from(attribute)
        .where(attribute.in(person.attributes),
               attribute.attributeName().name.toLowerCase().eq("eye color"),
               attribute.attributeValue.toLowerCase().eq("blue"))
         .exists()
    

    In addition to QueryDslPredicateExecutor you can also use Querydsl queries via Spring Data like this

    public class CustomerRepositoryImpl
     extends QueryDslRepositorySupport
     implements CustomerRepositoryCustom {
    
        public Iterable findAllLongtermCustomersWithBirthday() {
            QCustomer customer = QCustomer.customer;
            return from(customer)
               .where(hasBirthday().and(isLongTermCustomer()))
               .list(customer);
        }
    }
    

    Example taken from here https://blog.42.nl/articles/spring-data-jpa-with-querydsl-repositories-made-easy/

提交回复
热议问题