java - JPA 实体图的目标是什么?

标签 java hibernate jpa entity entitygraph

我一直在学习 JPA,我发现我们可以使用自 JPA 2.1 以来的实体图。

但我还没有理解实体图的优点。

我知道使用实体图的优点之一是我们可以仅指定我们想要在整个实体中获取的数据,但是如果我们想要整个实体,是否还有其他理由使用实体图?

或者只有当我们想要检索部分数据时才应该使用实体图?

如果我们使用实体图还有其他目的或优点,我想知道。

最佳答案

JPA Entity Graph允许您覆盖默认的获取计划。

默认获取计划

正如我在 this article 中解释的那样,每个实体都有一个在实体映射期间定义的默认获取计划,并指示 Hibernate 如何获取实体关联。

默认情况下,@ManyToOne@OneToOne 关联使用 FetchTyp.EAGER 策略,从性能角度来看,这是一个糟糕的选择。因此,出于这个原因,最好将所有 @ManyToOne@OneToOne 关联设置为使用 FetchType.LAZY 策略,就像在以下示例:

@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {

    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    private String review;
    
    //Getters and setters omitted for brevity
}

使用 find 方法获取 PostComment 实体时:

PostComment comment = entityManager.find(PostComment.class, 1L);

Hibernate 执行以下 SQL 查询:

SELECT pc.id AS id1_1_0_,
       pc.post_id AS post_id3_1_0_,
       pc.review AS review2_1_0_
FROM post_comment pc
WHERE pc.id = 1

post 关联被获取为 Proxy只有 id 由上述 SQL 查询加载的 post_id 外键列设置。

当访问 post 代理的任何非 id 属性时:

LOGGER.info("The comment post title is '{}'", comment.getPost().getTitle());

执行辅助 SQL 查询,按需获取 Post 实体:

SELECT p.id AS id1_0_0_,
       p.title AS title2_0_0_
FROM post p
WHERE p.id = 1

-- The comment post title is 'High-Performance Java Persistence, part 1'

覆盖默认的获取计划

如果我们想覆盖默认的获取计划并在查询执行时急切地获取 post 关联,我们可以使用一个 JPQL 查询来指示 Hibernate 使用 FETCH JOIN 子句获取惰性关联:

PostComment comment = entityManager.createQuery("""
    select pc
    from PostComment pc
    left join fetch pc.post
    where pc.id = :id
    """, PostComment.class)
.setParameter("id", 1L)
.getSingleResult();

LOGGER.info("The comment post title is '{}'", comment.getPost().getTitle());

然后,默认的抓取计划将被覆盖,post 关联将被急切抓取:

SELECT pc.id AS id1_1_0_,
       p.id AS id1_0_1_,
       pc.post_id AS post_id3_1_0_,
       pc.review AS review2_1_0_,
       p.title AS title2_0_1_
FROM post_comment pc
LEFT JOIN post p ON pc.post_id = p.id
WHERE pc.id = 1

声明式 JPA 实体图

也可以使用 JPA 实体图覆盖默认的获取计划。例如,我们可以使用以下 JPA @EntityGraph 注释定义特定的获取计划:

@Entity(name = "PostComment")
@Table(name = "post_comment")
@NamedEntityGraph(
    name = "PostComment.post",
    attributeNodes = @NamedAttributeNode("post")
)
public class PostComment {
    //Code omitted for brevity
}

有了 PostComment.post 实体图,我们现在可以加载 PostComment 实体及其关联的 post 实体,如下所示:

PostComment comment = entityManager.find(
    PostComment.class, 
    1L,
    Collections.singletonMap(
        "javax.persistence.loadgraph",
        entityManager.getEntityGraph("PostComment.post")
    )
);

并且,当执行上述find 方法时,Hibernate 会生成以下 SQL SELECT 查询:

SELECT pc.id AS id1_1_0_,
       pc.post_id AS post_id3_1_0_,
       pc.review AS review2_1_0_,
       p.id AS id1_0_1_,
       p.title AS title2_0_1_
FROM post_comment pc
LEFT OUTER JOIN post p ON pc.post_id = p.id
WHERE pc.id = 1

如果您使用的是 Spring,则可以使用 @EntityGraph 注释在 Repository 方法中引用 JPA 实体图:

@Repository
public interface PostCommentRepository 
        extends CrudRepository<PostComment, Long> {

    @EntityGraph(
        value = "PostComment.post", 
        type = EntityGraphType.LOAD
    )
    PostComment findById(Long id);
}

程序化 JPA 实体图

如果您不喜欢注释,那么您也可以使用 JPA EntityManagercreateEntityGraph 方法以编程方式构建 JPA 实体图,如下所示示例:

EntityGraph<PostComment> postCommentGraph = entityManager
    .createEntityGraph(PostComment.class);
    
postCommentGraph.addAttributeNodes("post");

PostComment comment = entityManager.find(
    PostComment.class, 
    1L,
    Collections.singletonMap(
        "javax.persistence.loadgraph",
        postCommentGraph
    )
);

关于java - JPA 实体图的目标是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31703532/

相关文章:

ssl - OpenJDK 下不稳定的 SSL 证书路径验证

java - 将非静态列表转换为静态列表

java - 单击鼠标即可获取坐标

java - Hibernate 标准多选查询与连接

java - Maven接口(interface)方法之间的模糊引用

java - 以所有七种方式反射(reflect)方阵八分圆的算法

java - 从下拉列表中的数据库检索值(<s :select>) using Struts 2 and Hibernate

java - Hibernate:可嵌入列表的唯一约束(@ElementCollection)

java - 我可以在 JAXWS Web 服务方法中将 Hibernate 实体作为返回值返回吗?

java - 如何进行自定义 EJB/JPA 映射类型?