一:HQL介绍
1. 什么是HQL
HQL是Hibernate Query Language的缩写
2. hql和sql区别/异同
HQL SQL
类名/属性 表名/列名
区分大小写,关键字不区分大小写 不区分大小写
别名 别名
?(占位符),从下标0开始计算位置(hibernate5之后不支持) ?,从顺序1开始计算位置
支持:命名参数 不支持:命名参数
面向对象的查询语言 面向结构查询语言
例:sql:select name from t_mvc_book where name like ?,?,?,?,?,?,?,?,?
hql:from Book where name like :bookName,:price,:sex::age query.setParam('bookName':圣墟)
3. 处理返回的结果集
3.1 单个对象
select没有逗号
3.2 Object[]
b.bookId, b.bookName
3.3 Map
new Map(b.bookId as bid, b.bookName as bname)
3.4 new 构造方法(attr1,attr2)
new Book(b.bookId, b.price)
单个列段
4. hql中使用占位符
4.1 ?占位符
从下标0开始计算位置
hibernate5之后不再支持?占位符
4.2 :命名参数
5. 连接查询
6. 聚合函数
sum
avg
max
min
count
7. hql分页
int page = 2;// 页码:page
int row = 10;// 每页行数:rows
query.setFirstResult((page - 1) * row);// 设置起始记录下标
query.setMaxResults(row);// 设置返回的最大结果集
二:HQL语法基础
1.实体类
package com.xly.two.entity;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Book implements Serializable{
// book_id int primary key auto_increment,
// book_name varchar(50) not null,
// price float not null
private Integer bookId;
private String bookName;
private Float price;
private Set<Category> categories = new HashSet<Category>();
private Integer initCategories = 0;
public Integer getInitCategories() {
return initCategories;
}
public void setInitCategories(Integer initCategories) {
this.initCategories = initCategories;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Set<Category> getCategories() {
return categories;
}
public void setCategories(Set<Category> categories) {
this.categories = categories;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]";
}
public Book(Integer bookId, String bookName) {
super();
this.bookId = bookId;
this.bookName = bookName;
}
public Book() {
super();
}
}
3. HQLTest处理返回的结果集
package com.xly.three.hql;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.xly.two.entity.Book;
import com.xly.two.util.SessionFactoryUtil;
public class HqlTest {
private Session session;
private Transaction transaction;
@Before
public void before() {
session = SessionFactoryUtil.getSession();
transaction = session.beginTransaction();
}
@After
public void after() {
transaction.commit();
session.close();
}
/**
* 返回对象(多个)
*/
@Test
public void testList1() {
Query query &#