HQL查询:
HQL查询:
Hibernate Query Language
HQL是基于Java的查询,查询的是对象
HQL对象是区分大小写的
HQL中查询的是对象而不是表,并且支持多态
HQL主要通过QUERY来操作
Hibernate单表查询:
1 全表查询
Query是hibernate提供的类,query.list()会自动将结果对象组装到list中
Order是对象名,不是表名
Query<Order> query = session.createQuery("from Order", Order.class);
List<Order> list = query.list();
for(Order order : list) {
System.out.println(order);
}
2 别名查询
Query<Order> query = session.createQuery("select o from Order o", Order.class);
List<Order> list = query.list();
3 条件查询
Query<Order> query = session.createQuery("from Order where orderno = '111'", Order.class);
List<Order> list = query.list();
使用占位符
Query<Order> query = session.createQuery("from Order where orderno = ?", Order.class);
query.setParameter(0, "111");
List<Order> list = query.list();
4 具名查询
为名为orderno的占位符赋值
Query<Order> query = session.createQuery("from Order where orderno = :orderno", Order.class);
query.setParameter("orderno", "111");
List<Order> list = query.list();
5 分页查询
Query<Order> query = session.createQuery("from Order", Order.class);
//偏移量
query.setFirstResult(0);
//查询行数
query.setMaxResults(5);
List<Order> list = query.list();
6 查询排序
Query<Order> query = session.createQuery("from Order order by id desc", Order.class);
List<Order> list = query.list();
7 聚合查询
//注意:返回值是Long
Query<Long> query = session.createQuery("select count(*) from Order", Long.class);
//写法1:
/*List<Long> list = query.list();
//得到第0条记录
Long count = list.get(0);*/
//写法2:
Long count = query.uniqueResult();
System.out.println(count);
8 投影查询
投影查询:查询表中的某几个字段
Query<Object[]> query = session.createQuery("select orderno, productName from Order", Object[].class);
List<Object[]> list = query.list();
for(Object[] order : list) {
for(Object column : order) {
System.out.print(column);
System.out.print(" ");
}
System.out.println();
}
Query<Order> query = session.createQuery("select new com.roxy.hibernate.pojo.Order(orderno, productName) from Order", Order.class);
List<Order> list = query.list();
Hibernate多表查询:
1 内连接:
Query<Object[]> query = session.createQuery("select c.name, o.productName from Customer c inner join c.orders o", Object[].class);
List<Object[]> list = query.list();
for(Object[] order : list) {
for(Object column : order) {
System.out.print(column);
System.out.print(" ");
}
System.out.println();
}
2 左连接:
Query<Object[]> query = session.createQuery("select c.name, o.productName from Customer c left join c.orders o", Object[].class);
List<Object[]> list = query.list();
3 右连接:
Query<Object[]> query = session.createQuery("select c.name, o.productName from Order o right join o.customer c", Object[].class);
List<Object[]> list = query.list();