Hibernate中HQL语句写法

 

最开始项目中HQL语句写的比较随意,后来看了下Hibernate 中Query和Criteria API,和sql语句的编译过程 。了解到查询条件不要直接使用字符串拼接,可以大大提高sql语句执行效率,代码也更加规范安全。

1,hql中可以用"?"来占位,在使用query时,必须将"?"及其索引位置和字段名对应上(很容易出错;不利于维护;)

2,hql另外一种方式占位:命名参数;

使用命名参数;冒号+字段名(或别名);等于给原来的"?"起了个名字;
String hql = "from User as user where user.name=:name";
//....
query.setString ("name", name); // 此处第一个参数必须和hql中参数命名一致;

 

query 的基本写法:

  使用“=:xx” 标识变量

  setString("xx", ....)   插入对应的搜索条件

 

public String DocSerialNo(String perType, String organId) {
        String updateHql = "update LicenceSerialNo set curnum=curnum+1 where curareaid=:organId and areaid=:perType";    
        Query qr=this.getSession().createQuery(updateHql);
        qr.setString("organId", organId);
        qr.setString("perType", perType);
        int i=qr.executeUpdate();
        if(i<1)return null;
        String findSerialHql="from LicenceSerialNo  where curareaid=:organId and areaid=:perType";
        Query findQr=this.getSession().createQuery(findSerialHql);
        findQr.setString("organId", organId);
        findQr.setString("perType", perType);
        LicenceSerialNo licSerial=(LicenceSerialNo) findQr.list().get(0);    
        String licNo=licSerial.getLicencetype()+new DecimalFormat("0000").format(licSerial.getCurnum());
        return licNo;
    }

 
query的set系列方法很多,不需要都记住,使用的时候查询即可,重点掌握有特色的方法,如,
  query.setfirstResult(0); //  设置查询起始位置     

  query.setMaxResult(10);  //  设置查询记录数

这两个方法可以实现分页;这种方法可以实现不依赖于数据库(低耦合);

在hibernate.cfg.xml中的name为"dialect"(方言)的property来判断是哪种数据库,以方便采用对应数据库的分页实现:

    mysql就使用limit,Oracle就是用roll number;
query最常用的方法

  query.list()    query.uniqueResult()       set系列

 

 

criterial 使用:

  cr.add()   在sql语句后拼接查询限制条件

  Restrictions类提供了查询限制机制。它提供了许多方法,以实现查询限制.

Criteria cr = session.createCriteria(Student.class); //生成一个Criteria对象
cr.add(Restrictions.eq("name", "Bill"));//等价于where name=’Bill’
List list = cr.list();
Student stu = (Student)list.get(0);
System.out.println(stu.getName());

 

 

posted @ 2013-05-29 15:17  Little_cheeper  阅读(9215)  评论(0编辑  收藏  举报