使用CriteriaBuilder在Java中获取列表时引发IlLegalStateException

2022-06-15 00:00:00 criteria java jpa 休眠条件 predicate
总而言之,我有3个实体,主要的一个是名为"RAC"的实体。它包含一个"racNatureza"列表,该列表包含一个属性"Natureza"。

RAC

    @Entity
    @Table(name = "rac")
    public class Rac {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idRac;    

    @OneToMany(mappedBy = "rac", cascade = {CascadeType.ALL}, orphanRemoval = true)
    @JsonManagedReference //para evitar recursão infinita do JSON
    private List<RacNatureza> racNaturezas;

    //...getters and setters ok
}

racNatureza

@Entity
@Table(name = "rac_natureza")
public class RacNatureza implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_rac_natureza")
    private Long idRacNatureza;

    @ManyToOne
    @JsonBackReference //coloquei para evitar a recursao infinita de JSON
    @JoinColumn(name="id_rac")
    private Rac rac;

    @ManyToOne
    @JoinColumn(name="id_natureza")
    private Natureza natureza;

    @Column(name = "principal")
    private Boolean principal;
}

Natureza

@Entity
@Table(name = "natureza")
public class Natureza {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_natureza")
    private Integer idNatureza;
    private String descricao;

    @OneToMany(mappedBy = "natureza", fetch = FetchType.EAGER, orphanRemoval = true)
    @JsonIgnore
    private List<RacNatureza> racNatureza;
}

我正在尝试开发一个使用过滤器的搜索,在这种情况下,用户选择一个"Natureza"列表,然后,系统必须显示哪个"RAC"包含用户选择的Natureza。为此,我尝试使用EntityManager和CriteriaBuilder来实现。

我尝试这样编写表达式,但不起作用(我没有使用元模型):

@PersistenceContext
private EntityManager entityManager;

@Override
public List<Rac> filtrar(RacFilter racFilter) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Rac> criteria = builder.createQuery(Rac.class);
    Root<Rac> root = criteria.from(Rac.class);

    Predicate[] predicates = criarRestricoes(racFilter, builder, root);
    criteria.where(predicates);

    TypedQuery<Rac> query = entityManager.createQuery(criteria);
    return query.getResultList();

}

@Override
public Predicate[] criarRestricoes(RacFilter racFilter, CriteriaBuilder builder, Root<Rac> root) {
    List<Predicate> predicates = new ArrayList<>();
    if (racFilter.getNaturezas() != null) {
        predicates.add(
                builder.equal(root.<List<RacNatureza>>get("racNaturezas").<Natureza>get("natureza"), racFilter.getNaturezas()) );
    }   
    return predicates.toArray(new Predicate[predicates.size()]);
}
因此,使用上面的代码,我收到了以下错误: 由:java.lang.IlLegalStateException:非法尝试取消引用基本类型的路径源[null.racNaturezas]

我认为错误在这一行,但我真的不知道如何修复它:

    predicates.add(
            builder.equal(root.<List<RacNatureza>>get("racNaturezas").<Natureza>get("natureza"), racFilter.getNaturezas()) );
}   

解决方案

替换root.get("racNaturezas") 使用root.join("racNaturezas")

请不要问我为什么我们不能使用get

相关文章