Lazy fetching single column (class attribute) with Hibernate

你说的曾经没有我的故事 提交于 2019-11-28 09:10:39
TS-

From Hibernate, Chapter 19. Improving performance:

Lazy attribute fetching: an attribute or single valued association is fetched when the instance variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely necessary.

Alexey Alexeenka

For maven project it's needed to add following plugin dependency into pom.xml:

<plugin>
    <groupId>org.hibernate.orm.tooling</groupId>
    <artifactId>hibernate-enhance-maven-plugin</artifactId>
    <version>${hibernate.version}</version>
    <executions>
        <execution>
            <configuration>
                <failOnError>true</failOnError>
                <enableLazyInitialization>true</enableLazyInitialization>
            </configuration>
            <goals>
                <goal>enhance</goal>
            </goals>
        </execution>
    </executions>
</plugin>

I have checked it in my project and it works, example of entity:

@Entity(name = "processing_record")
public class ProcessingRecord {

/**
 * Why uuid: https://www.clever-cloud.com/blog/engineering/2015/05/20/why-auto-increment-is-a-terrible-idea/
 */
@Id
@Column(name = "record_id")
@org.hibernate.annotations.Type(type = "pg-uuid")
private UUID id;

...

/**
 * Processing result.
 */
@Column(name = "result")
@Basic(fetch = FetchType.LAZY)
private String result;
...

For more details take a look on following article: LINK

I am aware of the date of this inquiry, however, I would have also attempted to use a projection value class that maps as subset of the columns, and use that projection with a specified named query which instantiates that projection value object, instead of the base object being referenced here.

I am working on a solution which uses this method so I do not currently have a full example. However, the basic idea is that you will create a JPA query which uses the "select NEW Projection_Object_Target" syntax, where the fields are directly referenced within the constructor of "Projection_Object_Target".

I.E. Use a constructor expression as follows:

SELECT NEW fully.qualified.package.name.ProjectionObject(baseObject.column_target_0,baseObject.column_target_1,...,baseObject.column_target_n) FROM BaseObjectMappedInDBTable AS baseObject

Generic example use-case:

String queryStr =
  "SELECT NEW fully.qualified.package.name.ProjectionObject(baseObject.column_target_0) " +
  "FROM BaseObjectMappedInTable AS baseObject";
TypedQuery<ProjectionObject> query =
  em.createQuery(queryStr, ProjectionObject.class);
List<ProjectionObject> results = query.getResultList();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!