Hibernate Interview Questions Part IV

Difference between session.update() and session.lock() in Hibernate ?
  • Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object.

  • It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.

  • Each interaction with the persistent store occurs in a new Session. However, the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session and then "reassociates" them using Session.update() or Session.saveOrUpdate().

  • Learn More About Hibernate

  • You may also call lock() instead of update() and use LockMode.READ (performing a version check, bypassing all caches) if you are sure that the object has not been modified.

Cascade Save or Update in Hibernate ?

Cascade Save or Update - In one to Many- EXAMPLE

What does session.refresh() do ?

It is possible to re-load an object and all its collections at any time, using the refresh() method. This is useful when database triggers are used to initialize some of the properties of the object.

For Example - Trigger on cat_name column. Trigger is updating hit_count column in the same Cat Table. When Insert data into Cat TABLE trigger update hit_count coulmn to 1. sess.refresh() reload all the data. No need again to select call.

Difference between session.load() and session.get()?

Cat fritz = (Cat) session.load(Cat.class, "1");

Return the Cat Object with key 1. If there is no Cat Object with key 1 then throw will throw an unrecoverable exception. If the class is mapped with a proxy, load() just returns an uninitialized proxy and does not actually hit the database until you invoke a method of the proxy. This behaviour is very useful if you wish to create an association to an object without actually loading it from the database. It also allows multiple instances to be loaded as a batch if batchsize is defined for the class mapping.

Cat fritz = (Cat) session.get(Cat.class, "1");

If you are not certain that a matching row exists, you should use the get() method, which hits the database immediately and returns null if there is no matching row.

How will you configure Hibernate?

Step 1. Put Hibernate properties in the classpath.

Step 2. Put .hbm.xml in class path.

Code is here to create session ...

Learn more about Hibernate in our Video Tutorial

What is a Hibernate Session? Can you share a session object between different threads?

Session is a light weight and a non-threadsafe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete.

Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method.

Difference between session.save() and session.saveOrUpdate()?

session.save() - Insert data into the table.

session.saveOrUpdate() - Insert data if primary key not exist otherwise update .

How are joins handled using Hibernate.

Best way to handle is use of Criteria query.

Example : You have parent class.

.hbm.xml file

Get all the messages from message table where organisation id = <any id>

Criteria query is :

session.createCriteria(Message.class).createAlias("organization","org"). add(Restrictions.eq("org.orgId",new Long(orgId))).add(Restrictions.in("statusCode",status)).list();
What is the main advantage of using the Hibernate than using the SQL ?
  1. If you are using Hibernate then you don't need to learn specific SQL (like oracle,mysql), You have to user POJO class object as a table.

  2. Don't need to learn query tuning. Hibernate criteria query automatically tuned the query for best performance.

  3. You can use inbuild cache for storing data.

  4. No need to create own connection pool, we can use c3po. It will give best results.

  5. Don't need any join query which reduce performance and complex. Using hibernate you have to define in bean and hbm.xml file.

  6. You can add filter in Hibernate which execute before you query fires and get the best performance.

  7. EhCache is used for 2nd level cache to store all the redefined data like country table.