使用字段表示对象集合时如何使用过滤表达式创建规范?

How to create Specification with filtering expression when working with field represents collection of objects?

我有下一个实体:

附件:

@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 并且没有其他字段用于附件 equals 方法正常工作。

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