现在的位置: 首页 > 综合 > 正文

hql

2013年08月31日 ⁄ 综合 ⁄ 共 2538字 ⁄ 字号 评论关闭

本文转载自http://www.blogjava.net/focusJ/archive/2011/04/22/367245.html

HQL实例:

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

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

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

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

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

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

.setInteger("min", 2)

.setInteger("max", 8);

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

7. hibernate分页查询 

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

q.setMaxResults(3);

q.setFirstResult(0);

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

8. 多表连接查询:select t.title, c.name from Topic t 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 m where m.id between 3 and 5

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

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

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

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

13. 

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

 "upper(t.title)," +

 "trim(t.title)," +

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

 "length(t.title)" +

      " from Topic t ")

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

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

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

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

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

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

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

19. hql删除的三种方式:

Hibernate的删除方式:

/*方式一*/
String hql = "select p from Province as p where p.id=?";
Query query = session.createQuery(hql);
query.setString(0, id);
Province p = (Province)query.list().get(0);
session.delete(p);
/*方式二*/
String hql = "delete Province where id=?";
Query query = session.createQuery(hql);
query.setString(0, id);
int x = query.executeUpdate();
if(x>0){
  flag = true;
}
/*方式三*/
Province p = (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);

抱歉!评论已关闭.