左联接取不起作用

LEFT JOIN FETCH doesn#180;t work(左联接取不起作用)

本文介绍了左联接取不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于左联接取不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:左联接取不起作用

基础教程推荐