问题描述
假设我们有一个实体,它有10个字段。假设几乎所有这些字段都有非常大的数据。我们希望加载实体(不是字段集合!),并在运行时定义要加载的字段。我发现的解决方案建议使用构造函数。但是在10个字段的情况下,有必要在运行时定义字段是不可能的解决方案。有没有办法如何使用jpa 2.1解决这个问题?使用JPA 2.1 EntityGraph来定义要检索的字段通过查询。所以如果你有一个类 MyClass
,并且想要动态地检索特定的字段,像这样的东西就足够了 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,例如);
列表< MyClass> results = q.getResultList();
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?
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 - 加载运行时定义字段的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!