使用SpringData和QueryDSL-JPA查询映射值

时间:2017-07-17 13:47:15

标签: java jpa spring-data querydsl

我得到了以下数据结构

@Entity
public class Publication {
   private Map<Integer, Author> authors;
   // more stuff
}

@Entity
public class Author {
   private String name;
   // more stuff
}

我正在寻找一个查询dsl谓词,它给出了我的所有发布,其中任何Author.name包含某个字符串,例如“汉斯”

我试过了:

QPublication publication = QPublication.publication;
QAuthor author = QAuthor.author;
publication.authors.containsValue(JPAExpressions.selectFrom(author).where(author.lastName.containsIgnoreCase("Hans")));

但是,如果在名称中有多个作者包含“汉斯”,则会抱怨。是否像publication.authors.anyValue().name.equalsIgrnoreCase("Hans")那样像是有一个集合?

2 个答案:

答案 0 :(得分:1)

我找到了一个带有连接和自定义存储库实现的解决方案:

public class PublicationRepositoryImpl extends QueryDslRepositorySupport 
   implements PublicationRepositoryCustom {

@Override
public Page<Publication> findByAnyAuthorName(String name, PageRequest pageRequest) {
   QPublication publication = QPublication.publication;
   JPQLQuery<Publication> query = from(publication);
   QAuthor author = QAuthor.author;
   query.join(publication.authors, author);
   query.where(author.name.containsIgnoreCase(name);
   JPQLQuery<Publication> pagedQuery = getQuerydsl()
      .applyPagination(pageRequest, query);

   return PageableExecutionUtils.getPage(pagedQuery.fetch(), pageRequest,
    () -> query.fetchCount());
}

答案 1 :(得分:0)

我想你错过了 BooleanBuilder

在您的存储库中

- 试试这个

QPublication publication = QPublication.publication;
QAuthor author = QAuthor.author;
BooleanBuilder where= new BooleanBuilder();
where.and(publication.author.name.containsIgnoreCase(textToSearch));

//pass the where condition to the desired Repo method
repo.findAll(where);