Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: difference between session.get(EntityName.class, Id) and using Criteria

So far I've seen two approaches for retrieving objects from database (e.g. MySQL), one being session.get(EntityName.class, Id); and the other way being : criteria.add(Restrictions.eq('id', Id)).uniqueResult();

I find the first way handy when I want to update a single field in the object, I can use a setter to update the object and then commit a transaction, but I am not sure what are the differences between these two ways.

like image 336
TonyGW Avatar asked Feb 06 '26 01:02

TonyGW


1 Answers

Session.get()

If the instance is already associated with the session, return that instance.

Where as criteria always go to Database to get the particular row. Other than that the main difference you can find is prefer criteria queries for dynamic queries.

Consider that case

criteria.add(Restrictions.eq('this', that)).uniqueResult();
criteria.add(Restrictions.eq('this', that)).uniqueResult();
criteria.add(Restrictions.eq('this', that)).uniqueResult();
criteria.add(Restrictions.eq('this', that)).uniqueResult();
-----
criteria.uniqueResult();

You see there ....?? too many restriction right ? not possible with get().

like image 62
Suresh Atta Avatar answered Feb 09 '26 03:02

Suresh Atta