我有下一个实体:
附件:
@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<>();
}
我需要构建规范(我应该仅使用规范,因为文档服务是由第三方编写的,并且需要规范作为参数),其中必须包含按附件名称进行过滤。它应该看起来像这样:
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));
}
}
}
我尝试了很多解决方案,但都无法解决此任务。 主要问题是:
- 我不能做类似的事情:root.get("attachments").get("0"),即我不能在谓词中使用列表元素。当然,因为我有异常(exception)。
- 我无法使用 cb.in(),因为我只有 AttachmentFileName,并且没有其他字段可供附件
equals
方法正常工作。
最佳答案
if (attachmentFilteringName != null) { 结果 = 结果.and((根, 查询, cb) -> cb.equal(root.join("attachments").get("attachmentName"),attachmentFilteringName)); }
关于java - 当使用表示对象集合的字段时,如何使用过滤表达式创建规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57869368/