如何在 JPA/Eclipselink 2.6.5 中使用三个级别的"LEFT JOIN"来获取 Table3(关系一对一(?
此命令不获取它:(错误(
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 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");
我认为您需要在此处在表1和表2之间进行右连接,因此请使用"RIGHT JOIN"重试前两个示例。