Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate HQL where IN query

Im trying to return a SimpleQuery list that queries a single table and uses IN. I can get this to work using

return new List<Jobs>(
    ActiveRecordMediator<Jobs>.FindAll(Expression.In("ServiceId", ids))
);

However this is really really really slow. So id like to do something like this

SimpleQuery<Job> query = 
    new SimpleQuery<Job>(@"from Job as j where ? in (j.ServiceId)", ids);

return new List<Job>(query.Execute());

However I cant get the SimpleQuery to work. I cant find any documentation covering this and was hoping someone out there would be able to help.

Thanks

like image 346
Gilbert Avatar asked Mar 08 '10 14:03

Gilbert


People also ask

How do you write a subquery in HQL?

A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed. Note that HQL subqueries can occur only in the select or where clauses.

How use inner join in Hibernate query?

beginTransaction(); String select = "FROM Employee e INNER JOIN Team t ON e. Id_team=t. Id_team"; Query query = session. createQuery(select); List elist = query.

Is JPQL and HQL same?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.

Where HQL is used in hibernate?

Hibernate converts HQL queries into SQL queries, which are then used to perform database actions. Although Native SQL may be used directly with Hibernate, it is encouraged to utilize HQL wherever feasible to prevent database portability issues.


1 Answers

Have a look at the NHibernate HQL documentation here.

I'm guessing from your code, that you're after a HQL query to return all jobs where the job.ServiceID in a list of ids.

Maybe something along the lines,

IQuery q = s.CreateQuery("from Job as j where j.ServiceId in (:serviceIds)");
q.SetParameterList("serviceIds", ids); 

BTW, have you heard of the NHibernate Lambda Extensions project? Below is an example of the IN query done using the the mentioned library. Might be something interesting to look at as an alternative to using HQL.

DetachedCriteria after =
    DetachedCriteria.For<Person>()
        .Add(SqlExpression.In<Person>(p => p.Name, 
          new string[] { "name1", "name2", "name3" }));
like image 183
Noel Avatar answered Sep 28 '22 00:09

Noel