Hibernate的查询方式
hibernate的查询方式常见的主要分为三种: HQL, QBC(命名查询), 以及使用原生SQL查询(SqlQuery)
今天侧重讲HQL
*1:HQL*
口诀:见表写对象,见列写属性
基本查询有:
1. 1,查询表中所有数据
例子:
@Test
public void testhql(){
//查询所有
List<Prontion> prontion=session.createQuery("from Prontion").list();
for (Prontion prontion2 : prontion) {
System.out.println(prontion.toString());
}
}
2,查询某一列,返回值为;List
@Test
public void testhql(){
List<String> name=session.createQuery("select pname from Prontion").list();
for (String string : name) {
System.out.println(string);
}
}
3,带条件查询(直接设值,命名参数,索引方式)
4,between and
//带条件查询 加 between and
// 年龄12–15
@Test
public void testhql(){
List<Prontion>prontions=session.createQuery("from Prontion where page between :min and :max").setInteger("min", 12).setInteger("max", 15).list();
for (Prontion prontion : prontions) {
System.out.println(prontion.getPid());
}
}
5,聚合查询 ;unlqueResult(),结果就是字符串
例子:
@Test
public void testhql(){
int page=Integer.parseInt(session.createQuery("select max(page) from Prontion ").uniqueResult().toString());
System.out.println(page);
}
6,分页 setFirstResult() 第几条开始 setMaxResults()每页多少条
例子:
@Test
public void testhql(){
int pageNo=2;
int pageSize=2;
Listprontions=session.createQuery(“from Prontion”).setFirstResult((pageNo-1)*pageSize).list();
for (Prontion prontion : prontions) {
System.out.println(prontion);
}
}
7,排序
例子:
@Test
public void testhql(){
//排序
List<Prontion> prontions= session.createQuery("from Prontion order by page desc").list();
for (Prontion prontion : prontions) {
System.out.println(prontion);
}
}
8,构造查询 带参构造:select new对象(参数)from 表名所对应的实体类别名 采用数组:特殊情况(结果来源多个表)、 将二维数组转换封装成自己的对象(dto数据传输对象);
例子:
@Test
public void testhql(){
//构造查询
List<Prontion> prontions= session.createQuery("select new Prontion( pname,page) from Prontion").list();
for (Prontion prontion : prontions) {
System.out.println(prontion);
}
}
10,对象导航