gpt4 book ai didi

java - LEFT JOIN FETCH 不起作用

转载 作者:行者123 更新时间:2023-11-30 06:09:57 26 4
gpt4 key购买 nike

如何在 JPA/Eclipselink 2.6.5 中使用三级“LEFT JOIN”获取 Table3(关系 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 不支持嵌套获取联接。要解决此问题,您可以添加 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");

关于java - LEFT JOIN FETCH 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50478261/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com