Nhibernate Query Example (use HQL)

本文介绍使用 NHibernate 进行各种复杂查询的方法,包括简单的单表查询到涉及多表关联及子查询的高级查询技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

英文 看着都烦   没办法 代码英文最简单  囧。。 中文写的比英文都看的麻烦

=====  

Example 

PS

SQL  

1 .   Nomal             

2.    WHERE x = ?            

3.    WHERE x = ? and x1 = ? 

4.    WHERE ( x= ? and x1 = ? ) 

5.    WHERE ( x =? ) and ( x1 =?)

6.    WHERE ( x = ? ) o( x1 = ? r)

7.    FROM  T1 a ,T2 b  WHERE a.id = b.a_id AND b.x = ?  

8.    WHERE  x in (select x from T2 where x2 = ? )

9.     from T1 a , T2 b where a.id = b.a_id   and b.x =  ? 

10.  WHERE ( x  in  ( select x from T where T.x = ? )) 

11.  WHERE x  in ( SELECT a.x2  FROM T1 a , T2 b WHERE a.id = b.a_id  AND b.x3 = ? )

12.  WHERE ( x  in ( select a.id  from  T1 a , T2 b where ( b .x2 = ?  and a.id = b.a_id))); 

 

1.     Nomal

        var blog = s.Get<Blog>(1);  ||  var blog = s.Load<Blog>(1);          

 ==》   var name = s.Get<TableName>(x);   PS:x=id

SELECT * FROM TableName

 

2.   where x = ? 

        var blogs = s.CreateCriteria<Blog>()

                                    .Add(Restriction.Eq("Title","Ayende @ Rahien"))

                                    .List<Blog>();

==》    var name = s.CreateCriteria<TableName>()

                                    .Add(Restrictions.Eq("cloumName" , "cloum value"))

                                    .List<TableName>();

SELECT *

FROM    TableName

WHERE cloumName = cloum value

 

3.   where x = ? and x1 = ? 

        var blogs = s.CreateCriteria<Blog>()

                                    .Add(Restrictions.Eq("Title","Ayende @ Rahien"))

                                    .Add(Restrictions.Eq("Subtitle","Send me a patch for that"))

                                    .List<Blog>();

==》    var name = s.CreateCriteria<TableName>() 

                                    .Add(Restrictions.Eq("cloumName1" , "value"))

                                    .Add(Restrictions.Eq("cloumName2" , "value"))

                                    .List<TableName>();

SELECT *

FROM    TableName

WHERE cloumName1 = value1

AND      cloumName2 = value2

 

4.   where ( x= ? and x1 = ? ) 

       var blogs = s.CreateCriteria<Blog>()

                                       .Add(Restrictions.Disjunction()

                                       .Add(Restrictions.Eq("cloumName1" , "value"))

                                       .Add(Restrictions.Eq("cloumName2" , "value"))

                                    .List<Blog>();

            

==》    var name = s.CreateCriteria<TableName>() 

                                    .Add(Restrictions.Disjunction()

                                    .Add(Restrictions.Eq("cloumName1" , "value"))

                                    .Add(Restrictions.Eq("cloumName2" , "value"))

                                    .List<TableName>();

SELECT *

FROM    TableName

WHERE ( cloumName1 = value1

               OR      cloumName2 = value2 )

 

5.   where ( x =? ) and ( x1 =?)

      var blogs =   s.CreateCriteria<Blog>()    

                                      .Add(  Restrictions.Eq("Title" ,"Ayende @ Rahien" )   ||

                                                Restrictions.Eq("Subtitle" ,"Send me a patch for that" )

                                      .List<Blog>();

==》    var name =   s.CreateCriteria<TableName>()    

                                      .Add(  Restrictions.Eq("cloumName1" ,"value" )   ||

                                                Restrictions.Eq("cloumName2" ,"value" )

                                             ) 

                                      .List<TableName>();

                                                                           

SELECT * 

FROM    TableName

WHERE (cloumName1 =value)

              AND  (cloumName2 =value)

 

6.  where ( x = ? ) or ( x1 = ? )

var blogs = s.CreateQuery("from Blog b where b.Title = :title or b.Subtitle = :subtitle") 
.SetParameter("title","Ayende @ Rahien") 
.SetParameter("subtitle", "Send me a patch for that") 
.List<Blog>();

select * from tableName where  (cloum1 = value) or (cloum2 = value)

 

7.  FROM  T1 a ,T2 b  WHERE a.id = b.a_id AND b.x = ?  

var blogs = s.CreateCriteria<Blog>()

.CreateCriteria("Posts") 
.Add(Restrictions.Eq("Title","NHibernate Rocks")) 
.List<Blog>();


select * Blog b

inner join Posts p  

         on b.id = p.blogid

and  p.title = "NHibernate Rocks"     如何找 b

 

8. where x in (select x from T2 where x2 = ? )

var blogs = s.CreateCriteria<Blog>() 
.Add(Subqueries.PropertyIn("id", DetachedCriteria.For<Post>() 
.Add(Restrictions.Eq("Title","NHibernate Rocks")) 
.SetProjection(Projections.Property("Blog.id")) 
)) 
.List<Blog>();

select *                        --- subquery

from   Blogs 

where Id  in (select id from posts where title = "NHibernate Rocks")

 

9.  from T1 a , T2 b where a.id = b.a_id   and b.x =  ? 

var blogs = s.CreateQuery("from Blog b join b.Posts p where p.Title = :title") 
.SetParameter("title", "NHibernate Rocks") 
.List<Blog>();

select *

from blog

             inner join posts p  

                       on id = p.blogId

where (p.Title = "NHibernate Rocks")


 10 .  where  ( x  in  ( select x from T where T.x = ? )) 

var blogs = s.CreateQuery("from Blog b where b.id in (from Post p where p.Title =

                                                                        :title)") 
.SetParameter("title", "NHibernate Rocks") 
.List<Blog>();


select * from blog

where ( id in ( select p.id

                      from posts p

                      where (p.title = "NHibernate Rocks ")))

 

11.  WHERE x  in ( SELECT a.x2  FROM T1 a , T2 b WHERE a.id = b.a_id  AND b.x3 = ? )

var blogs = s.CreateCriteria<Blog>() 
.Add(Subqueries.PropertyIn("id", DetachedCriteria.For<Post>() 
.SetProjection(Projections.Property("Blog.id")) 
.CreateCriteria("User") 
.Add(Restrictions.Eq("Username","Ayende")))) 
.List<Blog>();

select * from blog

where id in ( select p.blogid 

                    from posts p

                             inner join User u 

                                       on p.UserId = u.id

                    where  u.Username = "Ayende")


12.  where ( x  in ( select a.id  from  T1 a , T2 b where ( b .x2 = ?  and a.id = b.a_id))); 

var blogs = s.CreateQuery("from Blog b where b.id in (from Post p where p.User.Username = :user)") 
.SetParameter("user","Ayende") 
.List<Blog>();

select * from blog  

where  (id in (select p.id  

                     from posts p , users u 

                     where (u.Username = "Ayende"

                                 and p.UserId = u.Id)));

 

 ==========================

 

 was the first day of my NHibernate course, and I think that it might be good to point out a few of the samples that we worked with. Those are pretty basic NHibernate queries, but they are probably going to be useful for beginners.

Let us take my usual Blog model, and see what kind of queries (and results) we can come up with:

image

Let us find a blog by its identifier:

var blog = s.Get<Blog>(1);

Which results in:

image

We can also try:

var blog = s.Load<Blog>(1);

Which would result in… absolutely no SQL queries. You can look at a more deep discussion of that here.

Now, let us try to search by a property:

var blogs = s.CreateCriteria<Blog>()
.Add(Restrictions.Eq("Title", "Ayende @ Rahien"))
.List<Blog>();

Which results in:

image

If we try to make the same with HQL, it would look:

var blogs = s.CreateQuery("from Blog b where b.Title = :title")
.SetParameter("title","Ayende @ Rahien")
.List<Blog>();

Which results in slight different SQL than using the criteria:

image 

What about trying a more complex conditional? Let us try to see comparing two properties:

var blogs = s.CreateCriteria<Blog>()
.Add(Restrictions.Eq("Title","Ayende @ Rahien"))
.Add(Restrictions.Eq("Subtitle", "Send me a patch for that"))
.List<Blog>();

Which results in:

image

Let us do that again, but using two properties using an OR:

var blogs = s.CreateCriteria<Blog>()
.Add(Restrictions.Disjunction()
.Add(Restrictions.Eq("Title", "Ayende @ Rahien"))
.Add(Restrictions.Eq("Subtitle", "Send me a patch for that")))
.List<Blog>();

Which would result in:

image

We can also execute the same SQL using the following syntax:

var blogs = s.CreateCriteria<Blog>()
.Add(
Restrictions.Eq("Title", "Ayende @ Rahien") || 
Restrictions.Eq("Subtitle", "Send me a patch for that")
)
.List<Blog>();

Doing the same using HQL would be:

var blogs = s.CreateQuery("from Blog b where b.Title = :title and b.Subtitle = :subtitle")
.SetParameter("title","Ayende @ Rahien")
.SetParameter("subtitle", "Send me a patch for that")
.List<Blog>();

Which results in:

image

And changing that to an OR is pretty self explanatory :-)

var blogs = s.CreateQuery("from Blog b where b.Title = :title or b.Subtitle = :subtitle")
.SetParameter("title","Ayende @ Rahien")
.SetParameter("subtitle", "Send me a patch for that")
.List<Blog>();

Giving us:

image

Let us try something a bit more complex, finding a blog by a post title:

var blogs = s.CreateCriteria<Blog>()
.CreateCriteria("Posts")
.Add(Restrictions.Eq("Title","NHibernate Rocks"))
.List<Blog>();

That gives us:

image

You will note that we force a load of the Posts collection. We can try something else, though:

var blogs = s.CreateCriteria<Blog>()
.Add(Subqueries.PropertyIn("id",
DetachedCriteria.For<Post>()
.Add(Restrictions.Eq("Title","NHibernate Rocks"))
.SetProjection(Projections.Property("Blog.id"))
))
.List<Blog>();

Which would give us the same result, but without loading the Posts collection:

image

This is a pretty common example of changing the way that we compute complex conditionals when we want to avoid wide result sets.

Let us do the same with HQL:

var blogs = s.CreateQuery("from Blog b join b.Posts p where p.Title = :title")
.SetParameter("title", "NHibernate Rocks")
.List<Blog>();

Which would result:

image

We have the same issue as with the first Criteria API, and we can resolve it in the same way:

var blogs = s.CreateQuery("from Blog b where b.id in (from Post p where p.Title = :title)")
.SetParameter("title", "NHibernate Rocks")
.List<Blog>();

And the same result as in the Criteria API show us:

image

And the final test, let us try to find a blog that has a post posted by a specific user:

var blogs = s.CreateCriteria<Blog>()
.Add(Subqueries.PropertyIn("id",
DetachedCriteria.For<Post>()
.SetProjection(Projections.Property("Blog.id"))
.CreateCriteria("User")
.Add(Restrictions.Eq("Username","Ayende"))
))
.List<Blog>();

And this give us:

image

The same thing with HQL will give us:

var blogs = s.CreateQuery("from Blog b where b.id in (from Post p where p.User.Username = :user)")
.SetParameter("user","Ayende")
.List<Blog>();

And that results:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值