I have 2 entities as Company and User.
User –> ManyToOne –> Company
SQL
select * from user where companyid in (select companyid from Company where companyName = ‘Company1′)
Now I can write this SQL in below 2 ways
1) Using Detached Criteria
DetachedCriteria subCriteria = DetachedCriteria.forClass(Company.class);
subCriteria.add(Restrictions.eq(" companyName ", companyName));
subCriteria.setProjection(Property.forName("companyid") );
Criteria criteria = session.createCriteria(User.class);
criteria.add(Subqueries. propertyIn("companyid", subCriteria));
criteria.list();
2) Using Criteria as
session.createQuery("From User u Where u.company.name like 'Company1'").list();
Question here is How many Objects will be loaded in hibernate Session ?
Does Company Object will be loaded into hibernate session ?
Both queries will load the found users in session. If the ManyToOne association is eagerly loaded (which is true by default), then each user’s company will also be loaded in the session. If it’s configured as lazy, then no company will be loaded in the session.
Note that the first query is a criteria query, whereas the second one is a HQL query (and not a Criteria query as you’re saying). The first query is also too complex. You don’t need any subquery (as the HQL query shows). You could simply do