Monu Mittal Monu Mittal - 1 year ago 93
MySQL Question

how to create inner query using criteria in hibernate?

I have a query like:

FROM mars_india.leave_x_user
WHERE user_id in (SELECT user_id FROM mars_india.user where vendor_id=16);

I got the following solution from stackoverflow but unable to understand it:

criteria =criteria.createCriteria(user.USER_DOMAINS)
.add(Restrictions.eq(UserDomain.DOMAIN, domain));

Answer Source

Well... first you'll need to understand that you dont't have to use a subquery to get the same information.

Try this query:

SELECT lxu.* FROM mars_india.leave_x_user lxu 
LEFT JOIN mars_india.user miu 
ON lxu.user_id = miu.user_id
WHERE miu.vendor_id=16

It should yield the same result as your query.

The JOIN statement is the magic. In simple words: it lets the two tables behave as one table. So now you can query this joined table with your vendor_id and return only the part of the joined table as a result that belogs to your "leave_x_user" table.

See, you only need one query with one restriction to get the same data.

That's what you are basically doing by using this criteria query.

In order to learn the syntax of the criteria query, take a look here:

If you want more specific information please post your domain model (the classes mapped to the tables).

Happy coding! :D

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download