为什么我不会在每个懒加载的关系上使用@BatchSize? [英] Why would I not use @BatchSize on every lazy loaded relationship?

查看:90
本文介绍了为什么我不会在每个懒加载的关系上使用@BatchSize?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hibernate的@BatchSize注释允许批量获取延迟加载的实体。例如。如果我有这样的东西:

  public class Product {


@OneToMany(fetchType = LAZY)
@BatchSize(size = 10)
私人ProductCategory类别;






现在如果我得到产品的类别,Hibernate将会获取最多10个产品的类别,这些产品在当前会话中尚未初始化其类别字段。这节省了大量的SQL调用到数据库。到现在为止还挺好。现在我想知道为什么我不会在每个延迟加载的关系上使用@BatchSize注释?毕竟为什么我需要额外的数据库调用?显然这肯定是有原因的,否则Hibernate的人可能会把它设为默认的,但我目前看不到它。

解决方案

我不会直接回答你的问题,但我会回答一个更通用的问题,可能是我发现了一些对我来说更快的工具,为什么不把它应用到任何地方?

简短的回答是:您不应该进行抢先式优化。



hibernate是一个非常棒的ORM,可以进行各种优化。您应该测量导致问题的所有流程(传统的 N + 1 即使速度很快,任何缓慢的进程等),并优化解决它。



您可能通过急于加载某些属性获得更好的性能,因为您总是使用他们,你可能需要一个其他的 BatchSize 为100,因为你知道这是关于你拥有该属性的关系数量。



最终,除非您需要关心它,否则您不应该关注优化。当你完成测量并发现问题时,你需要小心。


The @BatchSize annotation of hibernate allows for batched fetching of lazy-loaded entities. E.g. if i got something like:

public class Product {


    @OneToMany(fetchType=LAZY)
    @BatchSize(size=10)
    private ProductCategory category;

}

Now if I get the category of a product, Hibernate will fetch the categories of up to ten more products which are in the current session and have not yet had their category field initialized. This saves a ton of SQL calls to the database. So far so good. Now I wonder why would I not use the @BatchSize annotation on EVERY lazy loaded relationship? After all why would I want extra calls to the database? There clearly must be a reason for this, otherwise the Hibernate guys could have made it the default, but I currently can't see it.

解决方案

I am not going to answer to your question directly but I am going to answer a more generic question which could be "I have found something that works quicker for me, Why not apply it everywhere ?"

The short answer is : You should not do preemptive optimization.

hibernate is a wonderful ORM that allows all kind of optimization. You should measure all the processes that causes an issue (the classic N+1 even if it is fast, any slow processes, etc.) and optimize to solve it.

You might gain a lot better performance by eager loading some properties because you always use them, you might need a BatchSize of 100 for some other because you know it's about the number of relations you have for that property.

Ultimately, you should not care about optimization unless you need to care about it. And you need to care when you have done measurements and found issues.

这篇关于为什么我不会在每个懒加载的关系上使用@BatchSize?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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