gpt4 book ai didi

hibernate - 如何避免在实体的 hibernate 条件中初始化 Eager 列

转载 作者:行者123 更新时间:2023-12-04 13:39:57 24 4
gpt4 key购买 nike

多个实体与@OnetoMany 关系和 Eager Loaded with an Entity 相关联。
在使用 Hibernate 标准获取数据时,相关的 Eager 列被初始化,这会导致我的项目出现性能问题,因为它很大并且有许多 Eager 加载关系。

在使用 hibernate 条件获取数据时避免初始化 Eager 列的最佳方法是什么。

最佳答案

你可以使用投影。如果您使用的是 Spring Data,它包含一些不错的帮助程序,请参阅 Baeldung: Spring Data JPA ProjectionsSpring Data JPA Reference详情。如果您直接使用 Hibernate,请参阅 Baeldung: JPA/Hibernate ProjectionHibernate JavaDoc Projection
Hibernate(直接引用自 Baeldung)

To project on multiple columns using JPQL, we only have to add all the required columns to the select clause:

Query query = session.createQuery("select id, name, unitPrice from Product");
List resultList = query.getResultList();

But, when using a CriteriaBuilder, we'll have to do things a bit differently:

CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root product = query.from(Product.class);
query.multiselect(product.get("id"), product.get("name"), product.get("unitPrice"));
List<Object[]> resultList = entityManager.createQuery(query).getResultList();
Here, we've used the method multiselect() instead of select(). Using this method, we can specify multiple items to be selected.

Another significant change is the use of Object[]. When we select multiple items, the query returns an object array with value for each item projected. This is the case with JPQL as well.

Let's see what the data looks like when we print it:

[1, Product Name 1, 1.40][2, Product Name 2, 4.30][3, Product Name 3, 14.00][4, Product Name 4, 3.90]As we can see, the returned data is a bit cumbersome to process. But, fortunately, we can get JPA to populate this data into a custom class.

Also, we can use CriteriaBuilder.tuple() or CriteriaBuilder.construct() to get the results as a list of Tuple objects or objects of a custom class respectively.


我建议阅读 Baeldung 文章,它有更详细的介绍。

关于hibernate - 如何避免在实体的 hibernate 条件中初始化 Eager 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58813422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com