gpt4 book ai didi

mysql - OneToOne Spring JPA MySQL LAZY加载N+1选择

转载 作者:行者123 更新时间:2023-11-29 11:57:08 25 4
gpt4 key购买 nike

在我的 Spring JPA/Data MySQL 应用程序中,我有以下实体:

public class Gene implements Serializable {

@Id
@Column(name = "uid")
private String uid;

@OneToOne(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "gene")
private GeneStory geneStory;

}

public class GeneStory implements Serializable {

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "gene_uid", referencedColumnName = "uid")
private Gene gene;

}

我正在尝试通过

加载所有 Gene
Query q = em.createQuery("select g from Gene g")
return q.getResultList();

我用 GeneStory 得到了 N+1 选择问题

现在,在数据库中的每个 Gene 上,我对 GeneStory 有额外的查询,如下所示:

select genestory0_.story_id as story_id1_7_0_ ... from gene_stories genestory0_ where genestory0_.gene_uid=?

由于某种原因,GeneStory 的延迟加载不起作用。

gene_storie表的数据库层我也有一个约束 -

CONSTRAINT `fk_gene_stories_gene_uid`
FOREIGN KEY (`gene_uid`)
REFERENCES `gene` (`uid`)

如何解决这个 N+1 选择问题?我不想将 GeneStoryGene 一起加载。我需要在需要时延迟加载它们。

最佳答案

根据 JPA 规范:

Lazy fetching is a hint to the persistence provider and can be specified by means of the Basic, OneToOne, OneToMany, ManyToOne, ManyToMany, and ElementCollection annotations and their XML equivalents

The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified.

关于mysql - OneToOne Spring JPA MySQL LAZY加载N+1选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33023359/

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