hibernate查询语言--hql

时间:2022-09-22 09:46:22

hql(hibernate query language)是一种查询语言。hql是完全面向对象的查询语言,可以理解如继承,多态,关联等概念。hql区分大小写,但是对应sql关键字(select、from、where)不区分。

新建一个java项目,结构如下:

hibernate查询语言--hql

实体类Book代码

@Entity
@Table(name="t_book")
@FilterDef(name="bf",parameters={@ParamDef(name="id",type="integer")})
@Filter(name="bf",condition="id <:id")
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private double price;
private String author;
private Date pubDate;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="category_id")
private Category category;
public Book() {
}
public Book(String name, double price) {
super();
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price
+ ", author=" + author + ", pubDate=" + pubDate + "]";
}
//省略get/set
}
Book.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">  
<class name="Book" table="t_book">
<id name="id">
<generator class="identity" />
</id>
<many-to-one name="category" class="Category" column="category_id" />
<property name="author" />
<property name="name" column="book_name" />
<property name="price" />
<property name="pubDate" />
<!-- 使用过滤器 -->
<filter name="bookFilter" condition="id=:id"></filter>

</class>
<!-- 过滤器定义 : 定义参数 -->
<filter-def name="bookFilter">
<filter-param name="id" type="integer" />
</filter-def>

</hibernate-mapping>
Category实体类

@Entity
@Table
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
//在多对一中的一端,设置了OneToMany后,必须指定mappedBy=多端的属性,这里的多端是Book
@OneToMany(mappedBy="category")
private Set<Book> books=new HashSet<Book>();
//省略get/set
}

Category.hbm.xml配置文件

<hibernate-mapping package="com.test.pojo">  
<class name="Category" >
<id name="id" >
<generator class="identity" />
</id>
<property name="name" />
<set name="books" inverse="true">
<key>
<column name="category_id" />
</key>
<one-to-many class="Book" />
</set>
</class>

</hibernate-mapping>
hibernate.cfg.xml配置文件

<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql:///hibernatetest
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>

<mapping resource="com/test/pojo/Book.hbm.xml" />
<mapping resource="com/test/pojo/Category.hbm.xml" />

<!-- <mapping class="com.test.pojo.Book" /> -->
<!-- <mapping class="com.test.pojo.Category" /> -->
</session-factory>
</hibernate-configuration>
HibernateUtil类

public class HibernateUtil {
private static Configuration cfg=null;
private static SessionFactory factory=null;
private static Session session=null;
static{
cfg=new Configuration().configure();
factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
}
public static Session getSession(){
if(factory!=null)
return session=factory.openSession();
factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
return session=factory.openSession();
}
public static void closeSession(){
if(session!=null && session.isOpen())
session.close();
}
}

HibernateTest测试类(该测试类所需的实体类使用注解方式或*.hbm.xml配置文件方式都可以测试,只需将hibernate.cfg.xml配置实体类映射修改即可)

public class HibernateTest {
@Test
public void testCreateDB(){
Configuration cfg=new Configuration().configure();
SchemaExport se=new SchemaExport(cfg);
se.create(true, true);
}
@Test
public void testSave(){
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Category category=new Category();
category.setName("文学");
Category category1=new Category();
category1.setName("科幻");
Category category2=new Category();
category2.setName("历史");
Category category3=new Category();
category3.setName("言情");
Category category4=new Category();
category4.setName("漫画");
Category category5=new Category();
category5.setName("悬疑");
Book book=new Book();
book.setName("读者");
book.setPrice(21.5);
book.setAuthor("读者出版传媒有限公司");
book.setPubDate(new Date());
book.setCategory(category);
Book book1=new Book();
book1.setName("蓝血人");
book1.setPrice(50);
book1.setAuthor("卫斯理");
book1.setPubDate(new Date());
book1.setCategory(category1);
Book book2=new Book();
book2.setName("傲慢与偏见");
book2.setPrice(80);
book2.setAuthor("简.奥斯丁");
book2.setPubDate(new Date());
book2.setCategory(category3);
Book book3=new Book();
book3.setName("中国历史");
book3.setPrice(21.5);
book3.setAuthor("人民");
book3.setPubDate(new Date());
book3.setCategory(category2);
Book book4=new Book();
book4.setName("七龙珠");
book4.setPrice(21.5);
book4.setAuthor("不知道");
book4.setPubDate(new Date());
book4.setCategory(category4);
Book book5=new Book();
book5.setName("名侦探柯南");
book5.setPrice(50);
book5.setAuthor("宫崎骏");
book5.setPubDate(new Date());
book5.setCategory(category5);


session.save(book);
session.save(book1);
session.save(book2);
session.save(book3);
session.save(book4);
session.save(book5);
tx.commit();
HibernateUtil.closeSession();
}
@Test
public void testGet(){
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
Book book=(Book) session.get(Book.class, 1);
System.out.println(book.getName()+"----"+book.getCategory().getName());
tx.commit();
HibernateUtil.closeSession();
}
//hql---hibernate query language
//查询单个属性
@Test
public void testQuery1(){
//查询所有书名
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
//Book 大写表示是com.test.pojo.Book类
String hql="select name from Book";
Query query=session.createQuery(hql);
//list()返回查询结果
//返回结果的类型是根据查询的列决定的
List<String> list=query.list();
for(String bookname:list){
System.out.println(bookname);
}
tx.commit();
HibernateUtil.closeSession();
}
//查询多个属性
@Test
public void testQuery2(){
//查询所有书的名称和价格
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
//Book 大写表示是com.test.pojo.Book类
//list()返回查询结果
//查询多个列时 返回结果是数组集合 数组中元素的类型是由查询列来决定
List<Object[]> list=session.createQuery("select name,price from Book").list();
for(Object[] objs:list){
System.out.println(objs[0]+"---"+objs[1]);
}
tx.commit();
HibernateUtil.closeSession();
}
//查询多个列时将查询结果封装为对象集合
@Test
public void testQuery3(){
//查询所有书的名称和价格
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
//Book 大写表示是com.test.pojo.Book类
//list()返回查询结果
//查询多个列时 返回结果是数组集合 数组中元素的类型是由查询列来决定
List<Book> list=session.createQuery("select new Book(name,price) from Book").list();
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 别名的使用
*/
@Test
public void testQuery4(){
//查询所有书的名称和价格
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
//Book 大写表示是com.test.pojo.Book类
//list()返回查询结果
//查询多个列时 返回结果是数组集合 数组中元素的类型是由查询列来决定
List<Book> list=session.createQuery("select new Book(b.name,b.price) from Book as b").list();
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 查询所有列 不能使用*号
*/
@Test
public void testQuery5(){
//查询所有书的名称和价格
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
//Book 大写表示是com.test.pojo.Book类
//list()返回查询结果
//查询多个列时 返回结果是数组集合 数组中元素的类型是由查询列来决定
List<Book> list=session.createQuery("from Book").list();
//查询所有列不能使用select * 可以使用别名 select b from Book b
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
//条件查询 占位符从0开始
//使用setInteger(0,4)或者是使用setParameter(0,4),setParameter不用理会参数类型
@Test
public void testQuery6(){
//查询所有书的名称和价格
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
List<Book> list=session.createQuery("from Book b where id<?")
.setInteger(0, 4)
.list();
//查询所有列不能使用select * 可以使用别名 select b from Book b
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
//条件查询 命名查询--设置条件参数的名称 以冒号开头后更改名称 设置参数时,只需指定名
@Test
public void testQuery7(){
//查询所有书的名称和价格
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
List<Book> list=session.createQuery("from Book b where id<:id")
.setParameter("id", 4)
.list();
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 分页查询
*/
@Test
public void testQuery8(){
//查询所有书的名称和价格
//创建Query对象
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
List<Book> list=session.createQuery("from Book b")
.setFirstResult(0) //开始显示的记录下标(currentPage-1)*pageSize
.setMaxResults(3) //设置每页记录数pageSize
.list();
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 聚合函数--统计查询
*/
@Test
public void testQuery9(){
//查询图书总数
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
//值类型可能是int,long 根据数据大小变化
Number count= (Number) session.createQuery("select count(b.name) from Book b")
.uniqueResult();
// Object count= session.createQuery("select max(b.price) from Book b")
// .uniqueResult();
System.out.println("总数:"+count.intValue());
tx.commit();
HibernateUtil.closeSession();
}
/**
* 分组查询
*/
@Test
public void testQuery10(){
//查询图书总数
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
List<Object[]> list= session.createQuery("select b.category.name,count(b.id) from Book b group by b.category.name")
.list();
for(Object[] objs:list){
System.out.println(objs[0]+"---"+objs[1]);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 排序
*/
@Test
public void testQuery11(){
//查询图书总数
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
List<Book> list= session.createQuery("from Book order by price desc")
.list();
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 对象导航--连接查询
*/
@Test
public void testQuery12(){
//查询科幻有关书籍
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
String hql="from Book b where b.category.name=:name";
hql="select b from Book b join b.category c where c.name=:name";
hql="select b from Book b inner join b.category c where c.name=:name";
List<Book> list= session.createQuery(hql)
.setString("name", "科幻")
.list();
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 左外连接
*/
@Test
public void testQuery13(){
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
String hql="select c.name, b.name from Category c left outer join c.books b";
List<Object[]> list= session.createQuery(hql)
.list();
for(Object[] objs:list){
System.out.println(objs[0]+"----"+objs[1]);
}
tx.commit();
HibernateUtil.closeSession();
}
/**
* 过滤器的使用--过滤查询--为查询加上某些条件
* 1、定义过滤器
* 2、使用,加条件
* 3、在查询时使得过滤器生效
*/
@Test
public void testQuery14(){
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
//配置文件方式,启用过滤器
session.enableFilter("bookFilter").setParameter("id", 4);
//注解方式,启用过滤器
//session.enableFilter("bf").setParameter("id", 4);
List<Book> list= session.createQuery("from Book")
.list();
for(Book b:list){
System.out.println(b);
}
tx.commit();
HibernateUtil.closeSession();
}

}
具体运行结果在此不做展示,感兴趣的可以自己运行测试。