Hibernate 的查询语句




1 最简单的查询

List<Special> specials =(List<Special>)session.createQuery("select spe from Specialspe").list();

2.基于 ? 的参数化形式

List<Student>students = (List<Student>)session.createQuery("select stu fromStudent stu where name like ?") .setParameter(0, "%%") .list();

    3.基于 :xx 的别名的方式设置参数

 List<Student> students =(List<Student>)session.createQuery("select stu from Student stuwhere name like :name and sex like :sex").setParameter("name","%%").setParameter("sex","%%").list();                                   4.如果返回的值只有一个,可以使用uniqueResult方法

    Longstu = (Long)session.createQuery("select count(*) from Student stu wherename like :name and sex like :sex").setParameter("name", "%%").setParameter("sex","%%").uniqueResult();

5.基于投影的查询基于投影的查询,如果返回多个值,这些值都是保存在一个object[]数组当中)

List<Object[]> stus =(List<Object[]>)session.createQuery("select stu.name, stu.sex fromStudent stu where name like :name and sex like:sex").setParameter("name", "%%").setParameter("sex","%%").list();

 

 

6.基于导航对象的查询

List<Student> stus =(List<Student>)session.createQuery("select stu from Student stuwhere stu.room.name like :room and sex like:sex").setParameter("room", "%计算机应用%").setParameter("sex","%%").list();

7.使用in 进行列表查询

   List<Student> stus =(List<Student>)session.createQuery("select stu from Student stuwhere stu.room.id in (:room) and stu.sex like:sex").setParameterList("room", new Integer[]{1, 2}).setParameter("sex","%%").list();

8.分页查询

List<Student> stus =(List<Student>)session.createQuery("select stu from Student stuwhere stu.room.name like :room and sex like:sex").setParameter("room", "%计算机应用%").setParameter("sex","%%").setFirstResult(0).setMaxResults(10).list();

你可能感兴趣的:(Hibernate)