本文介紹了使用CriteriaBuilder在Java中獲取列表時引發IlLegalStateException的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
總而言之,我有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
這篇關于使用CriteriaBuilder在Java中獲取列表時引發IlLegalStateException的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,