Write subquery in Criteria of nHibernate
Asked Answered
O

2

7

I've read about subquery in Criteria, but I am still unable to grasp it properly. Here I am taking one example and if somebody can help me write that using subquery it will be great.

Lets say we have table

Employee{EmployeeId.(int),Name(string),Post(string),No_Of_years_working(int)}

Now I want all the employees who are Managers and working for less than 10 years. I know that we can get the result without using subqueries but I want to use subquery just to understand how it works in criteria.

So, how I can write Criteria using subquery to get those employees.

Olshausen answered 6/5, 2010 at 7:9 Comment(0)
N
12

Well - the code should be something like this:

DetachedCriteria dc = DetachedCriteria.For<Employee>()
.Add (Subqueries.PropertyIn("EmployeeId",
     DetachedCriteria.For<Employee>()
         .SetProjection(Projections.Property("EmployeeId"))
         .Add(Restrictions.Lt("No_Of_years_working", 10))
         .Add(Restrictions.Eq("Post", "Manager"))
);

Hope this helps.

Nelly answered 6/5, 2010 at 8:14 Comment(0)
P
0

I was trying to perform something similar to Bipul's task, when I found this question, so I mainly got bernhardrusch's answer idea, but I've realized that without adding the Projections.projectionList the subquery do not work. So I've decided to drop a few lines of code with the final version:

Session session; //You get the session according with your app logic

//Let's define first the subquery
DetachedCriteria sub = DetachedCriteria.forClass(Employee.class);
sub.add( Restrictions.lt("No_Of_years_working", 10) );
sub.add( Restrictions.eq("Post", "Manager") );
sub.setProjection( 
Projections.projectionList().add(                   Projections.property("EmployeeId") 
) 
);

//Now the main query
Criteria criteria = session.createCriteria(Employee.class);
criteria.add( Property.forName("EmployeeId").in(sub) ); 
Paletot answered 12/2, 2013 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.