Hibernate - load objects with fields defined at runtime

Suppose we have some entity that has 10 fields. Suppose that almost all of these fields have very large data. And we want to load an object (not a set of fields!) And at runtime determine which fields to load. The solution that I found https://stackoverflow.com/a/228621/ ... suggests using a constructor. But in the case of 10 fields and the need to define fields at run time, a solution is not possible. Is there a way to solve this problem using jpa 2.1?

+3
source share
3 answers

Use JPA 2.1 EntityGraph to determine the fields that will be received in the request. Therefore, if you have a class MyClass and you want to receive separate fields dynamically, something like this might be enough

 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(); 
+2
source

With a Hibernate session, this can be obtained using a result transformer. Hibernate does not support result transformers for JPA.

HHH-8196 Custom ResultTransformer for JPA Criteria Queries

You can use unwrap(Session.class) to apply the result transformer to the session.

 List<Person> persons = entityManager.unwrap(Session.class). createQuery("select name as name from Person"). setResultTransformer( Transformers.aliasToBean(Person.class) ).list(); 

Additional information on nested projections

+1
source

Fetch graphs are primarily for selecting associations, not for individual fields.

Even if the JPA specification says that the default fields should be lazy, LAZY is just a hint of JPA providers who might ignore it. By default, Hibernate does not use lazy loading for fields. Only the default one-to-many and many-to-many LAZY .

To have lazy fields you need to enable bytecode support and possibly use @LazyGroup.

In any case, perhaps a DTO projection request is what you need first.

+1
source

All Articles