简体   繁体   English

Hibernate findById或SQL查询

[英]Hibernate findById or sql query

I have many time scenarios that I only want to access only one/two/ or some no of columns and we are using hibernate so I want to know which is better for performance either 我有很多时间场景,我只想访问一个/两个/或一些列,而我们正在使用休眠模式,所以我想知道哪种性能更好

1) by fetching findById method of hibernate, which is very convenient for me because I have to just call it, but I think it will be not good in performance because it will fetch all column rather I require only some. 1)通过获取hibernate的findById方法,这对我来说非常方便,因为我只能调用它,但是我认为它的性能不好,因为它将获取所有列,而我只需要其中一些。

2) Or by creating my query each time that is tedious but it will be better in performance 2)或通过每次创建乏味的查询来创建,但性能会更好

So I want suggestion regarding what should I use? 所以我想建议我应该使用什么?

To answer more specifically, it would be helpful if you included a code snippet. 为了更具体地回答,如果您包含一个代码片段,将很有帮助。 In general though, findById is a convenience method that will result in a query very similar to what you would write yourself. 但总的来说,findById是一种便捷的方法,它会导致查询与您自己编写的查询非常相似。 So writing the query yourself and returning only the columns you need (constructor expressions are useful) would be better in terms of performance. 因此,就性能而言,自己编写查询并仅返回所需的列(构造函数表达式很有用)会更好。 The question I would ask is, is that improved performance worth the more complicated code? 我要问的问题是,改进的性能值得更复杂的代码吗? You can always optimize your queries later. 您以后总是可以优化查询。

It entirely depends on the entity which is being loaded. 它完全取决于要加载的实体。 If the entity is one, with lots of relationships, and all you need is a couple of fields in the root entity, it is definitely worth writing your own query as Hibernate generates queries with JOIN s to load the entity which can be very expensive. 如果实体是一个实体,具有很多关系,并且您需要的只是根实体中的几个字段,那么绝对值得编写自己的查询,因为Hibernate会使用JOIN生成查询来加载该实体,这可能会非常昂贵。 The other thing to consider here is that, you can always handle the fields that are being loaded using LAZY or EAGER loading but these settings are static and will be applied permanently to your entity. 这里要考虑的另一件事是,您始终可以使用LAZYEAGER加载来处理正在加载的字段,但是这些设置是静态的,并将永久应用于您的实体。
On the other hand if the entity doesn't have many relationships, I believe the most expensive part is the conversation time between DB and your application, thus loading a number of extra fields can be ignored. 另一方面,如果实体没有很多关系,我认为最昂贵的部分是数据库与应用程序之间的对话时间,因此可以忽略加载许多额外的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM