本文介紹了左聯接取不起作用的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如何在JPA/lippselink 2.6.5中使用三個級別的”LEFT JOIN”來獲取表3(Relationship ONEtoONE)?
此命令不獲取它:(錯誤)
SELECT t1 FROM Table1 t1 LEFT JOIN FETCH t1.table2 t2
LEFT JOIN FETCH t2.table3
此命令獲取它,但不保留第一個”Left”:(錯誤)
SELECT t1 FROM Table1 t1 LEFT JOIN FETCH t1.table2
LEFT JOIN FETCH t1.table2.table3
這將獲取它,但它只有兩個級別:(不需要)
SELECT t2 FROM Table2 t2 LEFT JOIN FETCH t2.table3
表1:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "Id")
private Integer id;
@JoinColumn(name = "Table2", referencedColumnName = "Id")
@ManyToOne(fetch = FetchType.LAZY)
private Table2 table2;
表2:
@Id
@Basic(optional = false)
@NotNull
@Column(name = "Id")
private Integer id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "table2")
private Collection<Table1> table1Collection;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "table2")
private Table3 table3;
表3:
@Id
@Basic(optional = false)
@NotNull
@Column(name = "Id")
private Integer id;
@JoinColumn(name = "Table2", referencedColumnName = "Id", insertable = false, updatable = false)
@OneToOne(fetch = FetchType.LAZY, optional = false)
private Table2 table2;
謝謝!
推薦答案
JPA/JPQL不支持嵌套的FETCH聯接。要解決這個問題,您可以在查詢中添加一個query hint,以告訴它您希望使用左外部聯接來聯接什么。fetch-join查詢提示有一個更好的示例,說明如何使用它。
Query query = em.createQuery("SELECT t1 FROM Table1 t1", Table1.class);
query.setHint("eclipselink.LEFT_FETCH", "t1.table2");
query.setHint("eclipselink.LEFT_FETCH", "t1.table2.table3");
這篇關于左聯接取不起作用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,