【问题标题】:How to create Specification with filtering expression when working with field represents collection of objects?使用字段表示对象集合时如何使用过滤表达式创建规范?
【发布时间】:2019-09-10 10:59:18
【问题描述】:

我有下一个实体:

附件:

@Data
@ToString
@Entity
@EqualsAndHashCode
@Accessors(chain = true)
public class Attachment {
   private Long id;
   private String attachmentName;
   private String code;
}

文档:

@Data
@ToString
@Entity
@EqualsAndHashCode
@Accessors(chain = true)
public class Document{
   private Long id;
   private String documentName;

   @LazyCollection(LazyCollectionOption.FALSE)
   @OrderBy
   @OneToMany(mappedBy = "...", orphanRemoval = true, cascade = CascadeType.ALL)
   private List<Attachment> attachments = new ArrayList<>();
}

我需要构建规范(我应该只使用规范,因为文档服务是由第 3 方编写的并且需要规范作为参数),其中必须包含按附件名称进行的过滤。它应该看起来像这样:

public class DocumentPredicate {
   public Specification<Document> getPredicate(String attachmentFilteringName) {
      Specifications<T> result = Specifications.where(AnotherSpecification);

      if (attachmentFilteringName != null) {
            result = result.and((root, query, cb) ->
                    cb.equal(root.get("attachments"), attachmentFilteringName));
      }
   }

}

我尝试了很多解决方案,但都没有解决这个任务。 主要问题是:

  1. 我不能这样做:root.get("attachments").get("0"),即我不能在谓词中使用列表元素。因为我得到了例外,当然。
  2. 我不能使用 cb.in() 因为我只有 attachmentFileName 并且没有其他字段用于 Attachment equals 方法正常工作。

【问题讨论】:

    标签: java hibernate jpa orm criteria


    【解决方案1】:

    if (attachmentFilteringName != null) { result = result.and((root, query, cb) -> cb.equal(root.join("attachments").get("attachmentName"), attachmentFilteringName)); }

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2018-02-07
      相关资源
      最近更新 更多