gpt4 book ai didi

java - Hibernate引入二级缓存如何解决N+1问题?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:25:13 24 4
gpt4 key购买 nike

performance section的 Hibernate 文档指出:

A completely different approach to problems with N+1 selects is to use the second-level cache.

我不明白它如何解决问题。现实世界的例子和解释可能是什么?

最佳答案

很简单。假设您有以下域模型:

@Entity(name = "Post")
public class Post {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "post")
private List<Comment> comments = new ArrayList<>();

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Comment> getComments() {
return comments;
}

public void addComment(Comment comment) {
comments.add(comment);
comment.setPost(this);
}
}

@Entity(name = "Comment")
public class Comment {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
private Post post;

public Comment() {
}

public Comment(String review) {
this.review = review;
}

private String review;

public Long getId() {
return id;
}

public Post getPost() {
return post;
}

public void setPost(Post post) {
this.post = post;
}

public void setReview(String review) {
this.review = review;
}
}

如果您运行以下 HQL 查询:

List<Comment> comments = session.createQuery(
"select c from Comment c ").list();
for(Comment comment : comments) {
Post post = comment.getPost();
}

然后对于每个评论,您必须运行一个额外的查询来获取相关的评论帖子。

如果启用二级缓存:

@Entity(name = "Post")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Post {
...
}

然后 Hibernate 首先进入二级缓存加载实体,只有在没有找到缓存条目时才访问数据库。

一个更简单的解决方案是简单地 fetch all required data at query-time :

List<Comment> comments = session.createQuery(
"select c from Comment c fetch c.post ").list();

这样您就不会遇到 N+1 查询问题,也不需要二级缓存。 Like any caching solution ,当数据库在 Hibernate API 之外更新时,二级缓存容易出现不一致。

关于java - Hibernate引入二级缓存如何解决N+1问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29216629/

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