4

What advantages does get have over createQuery?

I can see there might be a slight performance improvement in not having to parse the HQL, but is there any other major advantage to using get over createQuery?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
B T
  • 57,525
  • 34
  • 189
  • 207

2 Answers2

5

First, it's much quicker to type, is much more readable, and expresses the intent clearly: get an entity by its ID. And it's basically impossible to make an error, whereas you could have a typo in your HQL query.

Regarding performance, the main advantage is that it executes a select statement only if the entity is not in the session cache yet. An HQL query will be executed every time. And if you have a second-level cache, get() will avoid executing a query completely if the entity is already in the second-level cache.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • So, according to this, you're not right about the performance of 'get': http://stackoverflow.com/questions/5370482/whats-the-advantage-of-load-vs-get-in-hibernate. Looks like you're actually talking about the performance of 'load'. – B T Mar 15 '13 at 06:59
  • Nope. `get()` looks if the entity is in the session cache. If it is already, it returns it. Else, it executes a SQL query to load it, puts it in the session cache, and returns it. `load()` checks if the entity is in the session cache. If it is already, it returns it. Else, it creates a lazy proxy, without even checking if the object exists in the database, and returns this proxy. Why don't you check it by yourself? Turn SQL logging on, and experiment. – JB Nizet Mar 15 '13 at 07:02
  • Interesting distinction. Where can I read more about this? The places I'm finding information on 'get' seem to all mention that it "always hits the database". Are they all repeating the same misinformation? – B T Mar 15 '13 at 07:08
0

get() uses directly session to retrieve objects.

  • get() only useful when you want to load an object i.e. SQL SELECT.
  • Like save() and persist() result in an SQL INSERT, delete() in an SQL DELETE and update() or merge() in an SQL UPDATE.
  • limited control and we need specify an entity that we need to extract.

createQuery() uses HQL

  • Using HQL we can write all CRUD queries.
  • give more control we can specify HQL(SQL like) clauses.
  • HQL is the own query language of hibernate and it is used to perform bulk operations on hibernate programs
  • An object oriented form of SQL is called HQL.
  • Here we are going to replace table column names with POJO class variable names and table names with POJO class names in order to get HQL commands
  • Sometimes it is very hard to write with other alternatives. Using HQL we can implement faster.
Premraj
  • 72,055
  • 26
  • 237
  • 180