Hibernate查询语句有哪些

小编给大家分享一下Hibernate查询语句有哪些,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

1. select子句

select 子句选择将哪些对象与属性返 回到查询结果集中. 考虑如下情况:

select mate   from Cat as cat       inner join cat.mate as mate

该语句将选择mates of other Cats。(其他猫的配偶) 实际上, 你可以更简洁的用以下的查询语句表达相同的含义:

select cat.mate from Cat cat

Hibernate查询语句可以返回值为任何类型的属性,包括返回类型为某种组件(Component)的属性:

select cat.name from DomesticCat cat  where cat.name like 'fri%'  select cust.name.firstName from Customer as cust

Hibernate查询语句可以返回多个对象和(或)属性,存放在 Object[]队列中,

select mother, offspr, mate.name   from DomesticCat as mother      inner join mother.mate as mate      left outer join mother.kittens as offspr

或存放在一个List对象中,

select new list(mother, offspr, mate.name)  from DomesticCat as mother      inner join mother.mate as mate      left outer join mother.kittens as offspr

也可能直接返回一个实际的类型安全的Java对象,

select new Family(mother, mate, offspr)  from DomesticCat as mother      join mother.mate as mate      left join mother.kittens as offspr

假设类Family有一个合适的构造函数.

你可以使用关键字as给“被选择了的表达式”指派别名:

select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n  from Cat cat

这种做法在与子句select new map一起使用时最有用:

select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )  from Cat cat

该Hibernate查询语句返回了一个Map的对象,内容是别名与被选择的值组成的名-值映射。

3. 聚集函数

HQL查询甚至可以返回作用于属性之上的聚集函数的计算结果:

select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)  from Cat cat

受支持的聚集函数如下:

avg(...), sum(...), min(...), max(...)    count(*)    count(...), count(distinct ...), count(all...)

你可以在选择子句中使用数学操作符、连接以及经过验证的SQL函数:

select cat.weight + sum(kitten.weight)   from Cat cat       join cat.kittens kitten  group by cat.id, cat.weight  select firstName||' '||initial||' '||upper(lastName) from Person

关键字distinct与all 也可以使用,它们具有与SQL相同的语义.

select distinct cat.name from Cat cat   select count(distinct cat.name), count(cat) from Cat cat

3. 多态查询

一个如下的Hibernate查询语句:

from Cat as cat

不仅返回Cat类的实例, 也同时返回子类 DomesticCat的实例. Hibernate 可以在from子句中指定任何 Java 类或接口. 查询会返回继承了该类的所有持久化子类 的实例或返回声明了该接口的所有持久化类的实例。下面的查询语句返回所有的被持久化的对象:

from java.lang.Object o

接口Named 可能被各种各样的持久化类声明:

from Named n, Named m where n.name = m.name

注意:***的两个查询将需要超过一个的SQL SELECT.这表明order by子句 没有对整个结果集进行正确的排序. (这也说明你不能对这样的查询使用Query.scroll()方法.)

以上是“Hibernate查询语句有哪些”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注蜗牛博客行业资讯频道!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接