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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With