Reputation: 18895
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.
Upvotes: 3
Views: 727
Reputation: 122006
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()
.
Upvotes: 4