左联接取不起作用

2022-04-02 00:00:00 java jpa eclipselink

如何在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");

相关文章