1

How to fetch the Table3 (relationship OneToOne), using three levels of "LEFT JOIN" in JPA /Eclipselink 2.6.5?

This command don´t fetch it: (Wrong)

SELECT t1 FROM Table1 t1 LEFT JOIN FETCH t1.table2 t2
                         LEFT JOIN FETCH t2.table3

This command fetch it, but don´t keep first "LEFT": (Wrong)

SELECT t1 FROM Table1 t1 LEFT JOIN FETCH t1.table2
                         LEFT JOIN FETCH t1.table2.table3

This fetch it, but it is two levels only: (Unwanted)

SELECT t2 FROM Table2 t2 LEFT JOIN FETCH t2.table3

Table1:

@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;

Table2:

@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;

Table3:

@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;

Thanks!

K.Nicholas
  • 10,956
  • 4
  • 46
  • 66
mwramos
  • 11
  • 3
  • What is the SQL generated from your various attempts? EclipseLink 2.4+ should support nested join fetches in JPQL https://stackoverflow.com/a/16693590/496099 – Chris May 23 '18 at 17:53

2 Answers2

1

JPA/JPQL doesn't support nested fetch joins. To get around this, you can add a query hint to your query to tell it what you want joined using a left outer join. The fetch-join query hint has a better example showing how it is used.

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");
Chris
  • 20,138
  • 2
  • 29
  • 43
0

I think you need to do a right join between table1 and table2 here, so retry both of your first two examples using ´RIGHT JOIN` instead.

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52