简体   繁体   English

如何在休眠中使用条件创建内部查询?

[英]how to create inner query using criteria in hibernate?

I have a query like: 我有一个查询,如:

SELECT * 
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: 我从stackoverflow获得了以下解决方案,但无法理解:

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

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. JOIN语句是魔术。 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. 因此,现在您可以使用vendor_id来查询此联接表,并仅返回联接表的一部分,该结果将记录到“ leave_x_user”表中。

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: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html 为了学习标准查询的语法,请在此处查看: https : //docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html

If you want more specific information please post your domain model (the classes mapped to the tables). 如果您需要更多具体信息,请发布您的域模型(映射到表的类)。

Happy coding! 编码愉快! :D :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM