【问题标题】:Or operator in spring specification not working或弹簧规范中的操作员不起作用
【发布时间】:2021-09-10 17:57:57
【问题描述】:

我正在尝试使用 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]));
}

我也尝试编写 2 个单独的规范方法并将它们与 Specification.where(specB).or(specC); 结合,但它也不起作用。

但是,当我使用基本的 Spring Data Jpa 方法 FindAllByEntityBIdOrEntityCId(int idB, int idC) 时,它运行良好

我无法弄清楚我做错了什么。我得到一个空的结果。

【问题讨论】:

  • 当你使用 spring.jpa.show-sql=true (application.properties) 时会发生什么?

标签: java spring hibernate spring-mvc spring-data-jpa


【解决方案1】:

toArray(new Predicate[0])方法调用有问题。

由于谓词的数量为两个,您应该创建一个大小为 2 的谓词数组,如下所示:

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()]));
    };
}

【讨论】:

  • 这不起作用。我试过toArray(new Predicate[predicates.size()])
  • 另外,我可以看到您的代码中有很多语法错误。您应该使用CriteriaBuilderequal() 方法而不是equals()。你能试试我在答案中更新的方法吗?
  • 不工作。 EntityA 正在映射数据库视图而不是表。有关系吗?
猜你喜欢
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 2011-01-02
  • 2011-06-22
  • 2013-05-05
  • 2014-02-15
相关资源
最近更新 更多