我正在尝试使用spring规范搜索视图,但无法使or运算符工作。
这是我的实体
@Entity
@Getter
@Immutable
public class EntityA {
@Id
@GeneratorValue(strategy = GenerationType.IDENTITY)
private Integerid;
private String content;
@ManyToOne
private EntityB entityB;
@ManyToOne
private EntityC entityC;
}
我的方法
Page<EntityA> page = repository.findAll(EntityARepository.specification(id), pageable);
EntityARepository 中的我的规范方法
static Specification<EntityA> specification(int id) {
return (tx, cq, cb} -> {
Predicate predicateB = cb.equals(tx.get("entityB").get("id"), id);
Predicate predicateC = cb.equals(tx.get("entityC").get("id"), id);
List<Predicate> predicates = Lists.of(predicateB, predicateC);
return cb.or(predicates.toArray(new Predicate[0]));
}
我还尝试编写了两种单独的规范方法,并将它们与Specification.where(specB).or(specC);
相结合,但也不起作用。
然而,当我使用基本的Spring Data Jpa方法FindAllByEntityBIdOrEntityCId(int idB, int idC)
时,它运行良好
我不明白自己做错了什么。我得到了一个空的结果。
toArray(new Predicate[0])
方法调用有问题。
由于谓词的数量是两个,您应该创建一个大小为二的谓词数组,如下所示:
cb.or(predicates.toArray(new Predicate[2]));
此外,您的方法包含许多语法错误。请尝试以下方法:
public static Specification<EntityA> specification(final int id) {
return (root, query, criteriaBuilder) -> {
Predicate predicateB = criteriaBuilder.equal(root.<EntityB>get("entityB").<Integer>get("id"), id);
Predicate predicateC = criteriaBuilder.equal(root.<EntityC>get("entityC").<Integer>get("id"), id);
List<Predicate> predicates = Arrays.asList(predicateB, predicateC);
return criteriaBuilder.or(predicates.toArray(new Predicate[predicates.size()]));
};
}