Hibernate中通过JPA entity graph的方式实现动态数据获取

来源:互联网 发布:ping 0端口 编辑:程序博客网 时间:2024/06/01 18:15

从JPA 2.1开始,JPA提供了新的定义数据获取策略的方式,那就是entity graph。通过entity graph,JPA应用可以在运行时将数据获取策略设置为EAGER的关联动态修改为LAZY。

1. 在Entity类中定义EntityGraph

@Entity(name = "Employee")@NamedEntityGraph(name = "employee.projects",    attributeNodes = @NamedAttributeNode("projects"))

注意这里用到的JPA的标注。

2. 在JPA EntityManager中使用定义的EntityGraph

Employee employee = entityManager.find(    Employee.class,    userId,    Collections.singletonMap(        "javax.persistence.fetchgraph",        entityManager.getEntityGraph( "employee.projects" )    ));

注意EntityGraph的用法。

1 0
原创粉丝点击