您的位置:首页 > Web前端

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

2016-07-27 10:21 537 查看
从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的用法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息