Hibernate - 加载具有在运行时定义的字段的实体 [英] Hibernate - load entities with fields defined at runtime

查看:24
本文介绍了Hibernate - 加载具有在运行时定义的字段的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个实体,它有 10 个字段.让我们假设几乎所有这些领域都有非常大的数据.我们想要加载实体(不是字段集!)并在运行时定义要加载的字段.我找到的解决方案 https://stackoverflow.com/a/24710759/5057736 建议使用构造函数.但是如果有 10 个字段并且需要在运行时定义字段是不可能的解决方案.有没有办法使用 jpa 2.1 解决这个问题?

Lets suppose we have some entity, which has 10 fields. And let's suppose that almost all these fields have very large data. And we want to load entity (not the set of fields!) and at runtime define which fields to load. The solution I found https://stackoverflow.com/a/24710759/5057736 suggests using constructor. But in case of 10 fields and that it is necessary to define fields at runtime is not possible solution. Is there a way how to solve this problem using jpa 2.1?

推荐答案

使用 JPA 2.1 EntityGraph 定义查询要检索的字段.因此,如果您有一个 MyClass 类,并且想要动态检索特定字段,这样的事情就足够了

Use a JPA 2.1 EntityGraph to define the fields to be retrieved by the query. So if you have a class MyClass, and want to retrieve particular fields dynamically, something like this could suffice

EntityGraph<MyClass> eg = em.createEntityGraph(MyClass.class);
eg.addAttributeNodes("id");
eg.addAttributeNodes("name");
eg.addAttributeNodes("relation");

Query q = em.createQuery("SELECT b FROM MyClass b");
q.setHint("javax.persistence.fetchgraph", eg);
List<MyClass> results = q.getResultList();

这篇关于Hibernate - 加载具有在运行时定义的字段的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆