例如对于TUser类 1.实体查询 String hql = " from TUser"; 执行这条语句会返回TUser以及TUser子类的纪录。 注: 如果 TUser 类具有外键, 查询会报错!解决方法: select 别名.属性 from 类 as 别名. 没有别名.属性仍然报错! hql = "from java.lang.Object" 会返回数据库中所有库表的纪录。 where 语句 hql = "from TUser as user where user.name='yyy'"; 其中,as可以省略也一样 hql = "from TUser user where user.name='yyy'"; where子句中,我们可以通过比较运算符设定条件,如: =, <>, >, <, >=, <=, between, not between, in, not in, is, like等。 2.属性查询 List list = session.createQuery("select user.name, user.age from TUser as user").list(); 还可以在HQL中动态构造对象实例的方法,将数据封装。 List list = session.createQuery("select new TUser(user.name, user.age) from TUser as user").list(); Iterator it = list.iterator(); while(it.hasNext() ) { TUser user = (TUser)it.next(); System.out.println(user.getName()); } 但是要注意这里的TUser对象只是对name和age属性的封装,其他状态均未赋值,所以不能用它来进行更新操作。 也可以在HQL的Select子句中使用统计函数 "select count(*) ,min(user.age) from TUser as user" 也可以使用distinct关键字来删除重复纪录。 select distinct user.name from TUser as user; 3.实体的更新与删除 hibernate 2中需要先查询出实体,设置属性后再保存。 hibernate 3中,提供了更灵活的方式(bulk delete/update) 更新: Query query = session.createQuery("update TUser set age=18 where id=1"); query.executeUpdate(); 删除: session.createQuery("delete TUser where age>=18"); query.executeUpdate();
/*
Session session = getSession();
Transaction tx = null; try { tx = session.beginTransaction();
String hqlDelete = "delete UserContract where usercontractId = :id"; session.createQuery( hqlDelete ).setInteger("id", id ).executeUpdate(); tx.commit(); } catch (RuntimeException re) { log.error("delete contractType failed", re); if(tx != null) tx.rollback();
throw re; }finally{ session.close();
}
*/
4.分组与排序 Order by子句: from TUser user order by user.name, user.age desc Group by子句和Having子句 "select count(user), user.age from TUser user group by user.age having count(user)>10" 5.参数邦定 通过顺序占位符?来填充参数: 1)hibernate 2 中通过session.find方法来填充 session.find("from TUser user where user.name=?", "Erica", Hibernate.STRING); 多个参数的情况: Object[] args = new Object[] {"Erica", new Integer(20)}; Type[] types = new Type{Hibernate.STRING, Hibernate.INTEGER}; session.find("from TUser user where user.name=? and user.age=?", args, types); 2)通过Query接口进行参数填充: Query query = session.createQuery("from TUser user where user.name=? and user.age>?"); query.setString(0,"Erica"); query.setInteger(1, 20); 通过引用占位符来填充参数: String hql = "from TUser where name=:name"; Query query = session.createQuery(hql); query.setParameter("name","Erica"); 甚至可以将查询条件封装为一个JavaBean class UserQuery { private String name; private Integer age; //getter and setter } String hql = "from TUser where name=:name and age=:age"; Query query = session.createQuery(hql); UserQuery uq = new UserQuery(); uq.setName("Erica"); uq.setAge(new Integer(20)); query.setProperties(uq); //会调用里面的getter? query.iterate(); 6.联合查询 也可以使用 inner join,left outer join, right out join, full join 排列组合:form TUser, TAddress