HQL

来源:互联网 发布:笨方法学python ex49 编辑:程序博客网 时间:2024/06/08 01:06

HQL实例:

1. 查询表中的所有记录:from Category

2. 带有where子句的条件查询:from Category where c.name 'c5'

3. 结果根据某一字段排序:from Category order by c.name desc(desc表示降序排列,asc表示升序排列)

4. 去除重复记录获得单一记录:select distinct from Category order by c.name desc

5. 带有参数的查询:from Category where c.id :min and c.id :max。hql语句中’:min’ 表示的是参数,可以像jdbc中一样,为参数赋值。在hql中可以这样,这里也运用了链式编程:

session.createQuery("from Category where c.id :min and c.id :max")

.setInteger("min", 2)

.setInteger("max", 8);

6. 带参数hql查询的另外一种查询:from Category where c.id and c.id ?

7. hibernate分页查询 

Query session.createQuery("from Category order by c.name desc");

q.setMaxResults(3);

q.setFirstResult(0);

其中setMaxResult()是设置每页的最大显示量,setFirstResult()是设置其实元素从哪里开始,这里0代表最后一条元素。

8. 多表连接查询:select t.title, c.name from Topic join t.category c

9. HQL函数:

a) Count():select count(*) from Msg m

b) Max()-min()-avg():select max(m.id), min(m.id), avg(m.id), sum(m.id) from Msg m

c) Between:from Msg where m.id between and 5

d) In:from Msg where m.id in (3, 4, 5)

10. Is null;is not null:from Msg where m.cont is not null

11. Is empty:from Topic where t.msgs is empty

12. Like:from Topic where t.title like '%5''%'匹配所有字符,'_'匹配单个字符。

13. 

一些功能函数,但是不重要了解即可:select lower(t.title)," +

 "upper(t.title)," +

 "trim(t.title)," +

 "concat(t.title, '***')," +

 "length(t.title)" +

     from Topic ")

Trim()是去掉首尾空格,返回字符串的副本,concat()将字符串欲查询出的字符串连接。

14. Abs()-sqrt()-mod():select abs(t.id)," + "sqrt(t.id)," "mod(t.id,2)" from Topic 

15. 获取当前的时间:select current_date, current_time, current_timestamp, t.id from Topic t

16. Having子句:select t.title, count(*) from Topic group by t.title having count(*) <= 1

17. Existfrom Topic where not exists (select m.id from Msg where m.topic.id=t.id)

需要注意的一点:in同样可以实现exist的功能,但是exist的执行效率较高。

18. Update的用法:update Topic set t.title upper(t.title)

19. hql删除的三种方式:

Hibernate的删除方式:


String hql "select from Province as where p.id=?";
Query query session.createQuery(hql);
query.setString(0, id);
Province (Province)query.list().get(0);
session.delete(p);

String hql "delete Province where id=?";
Query query session.createQuery(hql);
query.setString(0, id);
int query.executeUpdate();
if(x>0){
  flag true;
}

Province (Province)session.get(Province.class, id);
session.delete(p);

方式一相对比较笨重。

方式二中的Hql语句不要加as 别名!

方式三是Hibernate自带的方法。

20. 查询表中的某些字段:

方法一:给这个类新建一个构造方法,传进去你想要的参数,然后hql语句可以这样写:

select new Class(c.name, c.date, c.sex) from Class

方法二:用JDBCsql语句:

Session.createSQLQuery(sql);

0 0
原创粉丝点击