HQL:Hibernate Query Language

  • 提供更加丰富灵活、更为强大的查询能力
  • HQL更接近SQL语句查询语法
  • 面向对象的查询
    • "from Children where cid<?"  :这里Children指的是类不是children表;cid指的是Children类中的对象而不是children表中的字段

HQL查询(单表)

以一对多关系映射为例(parent[1]<——>children[n])

简单查询

实体类

1.Parent.java

 package com.qf.entity;

 import java.util.HashSet;
import java.util.Set; public class Parent { private Long pid;
private String pname;
private Integer age;
private Set<Children> childs = new HashSet<>(); @Override
public String toString() {
return "Parent [pid=" + pid + ", pname=" + pname + ", age=" + age + "]";
} public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Set<Children> getChilds() {
return childs;
}
public void setChilds(Set<Children> childs) {
this.childs = childs;
} }

2.Children.java

 package com.qf.entity;

 public class Children {

     private Long cid;
private String cname;
private Character sex;
private Parent p; @Override
public String toString() {
return "Children [cid=" + cid + ", cname=" + cname + ", sex=" + sex + ", p=" + p + "]";
} public Long getCid() {
return cid;
}
public void setCid(Long cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public Character getSex() {
return sex;
}
public void setSex(Character sex) {
this.sex = sex;
}
public Parent getP() {
return p;
}
public void setP(Parent p) {
this.p = p;
}
}

注:两个实体类的toString()方法重写时

  • Parent类的toString()方法如果包含Set<Children>的属性,那么Children类的toString()方法就不能包含Parent的属性,否则查询输出对象信息时会陷入死循环,导致StackOverflowError
package com.qf.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateUtils { private static Configuration cfg ;
private static SessionFactory factory; static {
cfg = new Configuration().configure();
factory = cfg.buildSessionFactory();
} public static Session getCurrentSession() {
return factory.getCurrentSession();
}
}
@Test
/**
* HQL简单查询
*/
public void queryByHQL() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); Query query = session.createQuery("from Children");
List<Children> list = query.list(); for (Children children : list) {
System.out.println(children);
} tx.commit();
}

别名查询

String hql = "select c from Children c order by cid desc";

HQL中支持数据库的带有别名的查询

@Test
/**
* HQL别名查询
*/
public void queryByHQL02() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); // String hql = "select c from Children c";
String hql = "select c from Children c order by cid desc";
Query query = session.createQuery(hql);
List<Children> list = query.list(); for (Children children : list) {
System.out.println(children);
} tx.commit();
}

条件查询

参数绑定

  • 位置绑定

    String hql = "select c from Children c where cid<? and cname like ?";
    Query query = session.createQuery(hql);
    query.setParameter(0, 20L);
    query.setParameter(1, "%张%");
    • hql中参数以"?"代替
    • 索引从0开始
  • 名称绑定
    String hql = "select c from Children c where cid<:aaa and cname like :bbb";
    Query query = session.createQuery(hql);
    query.setParameter("aaa", 20L);
    query.setParameter("bbb", "%张%");
    • hql中参数以 ":自定义名称"的形式代替
    • 不使用索引,使用(名称,值)的形式
@Test
/**
* HQL条件查询
*/
public void queryByHQL03() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); /*//一个条件(位置绑定)
String hql = "select c from Children c where cid<?";
Query query = session.createQuery(hql);
query.setInteger(0, 3);*/ //多个条件(位置绑定)
/*String hql = "select c from Children c where cid<? and cname like ?";
Query query = session.createQuery(hql);
query.setParameter(0, 20L);
query.setParameter(1, "%张%");*/ //多个条件(名称绑定)
String hql = "select c from Children c where cid<:aaa and cname like :bbb";
Query query = session.createQuery(hql);
query.setParameter("aaa", 20L);
query.setParameter("bbb", "%张%"); List<Children> list = query.list(); for (Children children : list) {
System.out.println(children);
} tx.commit();
}

投影查询

查询表中部分字段

方式一:返回Object[ ]

@Test
/**
* HQL简单查询
*/
public void queryByHQL() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); Query query = session.createQuery("select cname,sex from Children");
List<Object[]> list = query.list(); for (Object[] objs : list) {
System.out.println(Arrays.toString(objs));
}
tx.commit();
}

方式二:返回实体类对象

实体类

  • 添加无参构造方法
  • 添加有参构造方法(构造方法参数是你所要查询的属性)
package com.qf.entity;

public class Children {

	private Long cid;
private String cname;
private Character sex;
private Parent p; public Children(String cname, Character sex) {
super();
this.cname = cname;
this.sex = sex;
} public Children() {
super();
} ......
}

测试方法

@Test
/**
* HQL简单查询
*/
public void queryByHQL() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); Query query = session.createQuery("select new Children(cname,sex) from Children");
List<Children> list = query.list(); for (Children children : list) {
System.out.println(children);
}
tx.commit();
}

分页查询

  • query.setFirstResult(int start):从第几条记录开始查询
  • query.setMaxResults(int num):本页一共查询多少条记录
@Test
public void query() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); String sql = "from Children";
Query query = session.createQuery(sql);
query.setFirstResult(2);
query.setMaxResults(3);
List<Children> list = query.list();
for (Children c : list) {
System.out.println(c);
} tx.commit();
}

分组查询

max()、min()、count()、sum()、avg()

Object obj = query.uniqueResult():返回唯一结果

@Test
/**
* HQL简单查询
*/
public void queryByHQL() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); Query query = session.createQuery("select pid,pname,count(*) from Parent group by pid"); List<Object[]> list = query.list(); for (Object[] objects : list) {
System.out.println(Arrays.toString(objects));
} tx.commit();
}

HQL查询(多表)

内连接查询

正常的内连接sql:select * from Children c inner join Parent p

HQL:"from Children c inner join c.p "

  • 其中c.p是Children类的Parent属性变量p
  • 返回的是对象数组
package com.qf.entity;

public class Children {

	private Long cid;
private String cname;
private Character sex;
private Parent p;
....
}
@Test
/**
* HQL简单查询
*/
public void queryByHQL() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); Query query = session.createQuery("from Children c inner join c.p "); List<Object[]> list = query.list(); for (Object[] objects : list) {
System.out.println(Arrays.toString(objects));
} tx.commit();
}

------------------------------console-------------------------------

[Children [cid=1, cname=张三8, sex=1, p=Parent [pid=1, pname=老张, age=45]], Parent [pid=1, pname=老张, age=45]]
[Children [cid=2, cname=张三0, sex=0, p=Parent [pid=1, pname=老张, age=45]], Parent [pid=1, pname=老张, age=45]]
[Children [cid=3, cname=张三2, sex=1, p=Parent [pid=1, pname=老张, age=45]], Parent [pid=1, pname=老张, age=45]]
...............
[Children [cid=28, cname=王五0, sex=0, p=Parent [pid=3, pname=老王, age=43]], Parent [pid=3, pname=老王, age=43]]
[Children [cid=29, cname=王五8, sex=0, p=Parent [pid=3, pname=老王, age=43]], Parent [pid=3, pname=老王, age=43]]
[Children [cid=30, cname=王五6, sex=1, p=Parent [pid=3, pname=老王, age=43]], Parent [pid=3, pname=老王, age=43]]

迫切内连接

Query query = session.createQuery("from Children c inner join fetch c.p ");

  • 普通内连接HQL的inner join后加上fetch即可
  • 效果:返回的是内连接的左边对象(该例中Parent作为Children属性)
@Test
/**
* HQL简单查询
*/
public void queryByHQL() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction(); Query query = session.createQuery("from Children c inner join fetch c.p "); List<Children> list = query.list(); for (Children c : list) {
System.out.println(c);
} tx.commit();
}

------------------------------console-------------------------------

Children [cid=1, cname=张三8, sex=1, p=Parent [pid=1, pname=老张, age=45]]
Children [cid=2, cname=张三0, sex=0, p=Parent [pid=1, pname=老张, age=45]]
Children [cid=3, cname=张三2, sex=1, p=Parent [pid=1, pname=老张, age=45]]
....................
Children [cid=28, cname=王五0, sex=0, p=Parent [pid=3, pname=老王, age=43]]
Children [cid=29, cname=王五8, sex=0, p=Parent [pid=3, pname=老王, age=43]]
Children [cid=30, cname=王五6, sex=1, p=Parent [pid=3, pname=老王, age=43]]

左外连接、右外连接(没有迫切右外连接)以及迫切左外连接使用也类似

八、hibernate的查询(HQL)的更多相关文章

  1. Hibernate的查询 HQL查询 查询某几列

    HQL 是Hibernate Query Language的简写,即 hibernate 查询语言:HQL采用面向对象的查询方式.HQL查询提供了更加丰富的和灵活的查询特性,因此Hibernate将H ...

  2. Hibernate中关于HQL查询返回List<Object>数据的结果集问题

    ---恢复内容开始--- 开发中遇到的一个小问题,使用Hibernate中的HQL查询时,使用query.list()查询出来的是一个List<Object>结果集 原来代码: publi ...

  3. 二。Hibernate 查询 HQL、SQL方式

    hibernate的查询1.HQL方式:所有查询都是根据java对象名来完成,对象名替换表名2.SQL方式:保留原来的sql查询风格3.可以通过设置第一条和最大条数来实现各种数据库的分页查询4.通过B ...

  4. 【Hibernate步步为营】--hql查询小介

    HQL 是指Hibernate Query Language,它是Hibernate的查询语言,拥有一套自己的查询机制,它的查询语句和SQL非常类似.在使用的时候可以非常快上手.HQL提供了基本上SQ ...

  5. hibernate学习系列-----(4)hibernate基本查询上篇:HQL基本查询

    紧接着上一篇,今天继续hibernate的学习总结,来聊一聊hibernate的基本查询方法,先说说HQL(hibernate Query Language):它是官方推荐的查询语言.在开始写代码之前 ...

  6. Hibernate【查询、连接池、逆向工程】

    前言 在Hibernate的第二篇中只是简单地说了Hibernate的几种查询方式....到目前为止,我们都是使用一些简单的主键查询阿...使用HQL查询所有的数据....本博文主要讲解Hiberna ...

  7. hibernate模糊查询

    hibernate模糊查询-Restrictions.ilike & Expression.like Criteria criteria = session.createCriteria(Ta ...

  8. HQL查询——HQL查询的基本用法

    HQL查询--HQL查询的基本用法 1.HQL语法类似于SQL语法,但是需要注意的是,HQL是一种完全面向对象的查询语言.SQL语言操作的对象是数据表.列等数据库对象,而HQL语言的操作对象是类.实例 ...

  9. Hibernate的查询方式总结

    Hibernate的查询方式大体有三种,分别是HQL QBC和SQL三种.在网上查阅一一些资料,做了一个简单的总结. 1. SQL sql 是面向数据库表查询,from 后面跟的是表名,where 后 ...

  10. Hibernate SQL查询 addScalar()或addEntity()

    本文完全引用自: http://www.cnblogs.com/chenyixue/p/5601285.html Hibernate除了支持HQL查询外,还支持原生SQL查询.          对原 ...

随机推荐

  1. linux性能分析工具Ntop

  2. route - 显示 / 操作IP选路表

    总览 SYNOPSIS route [-CFvnee] route [-v] [-A family] add [-net|-host] target [netmask Nm] [gw Gw] [met ...

  3. rm - 移除文件或者目录

    总览 rm [options] file... POSIX(Portable Operating System Interface 可移植的操作系统接口) 选项: [-fiRr] GNU 选项 (最短 ...

  4. 08.Linux系统启动root密码忘记及文件系统故障问题

    问题:root用户密码忘记了,在重置root密码时,出现文件系统故障,没有root密码进不去,怎么办? Error:UNEXPECTED INCONSISTENCY;RUN fsck MANUALIY ...

  5. 11-基于CPCI的中频功率放大收发板

    1.板卡参数介绍 无线输入口 无线发射口 1M~3GHZ,可调,步进100HZ(非跳频模式) 功率:≤﹢10±2.5 dBm 收发通道数 收发各1通道/板 中频输入输出 70MHz, 5MHz/30M ...

  6. 【串线篇】sql映射文件-分布查询(上)association 1-1

    1.场景 1把钥匙带1把锁 JavaBean:private Lock lock;//当前钥匙能开哪个锁: 1). interface KeyDao: public Key getKeyByIdSim ...

  7. 线程中的sleep()、join()、yield()方法有什么区别?

    sleep().join().yield()有什么区别? sleep() sleep() 方法需要指定等待的时间,它可以让当前正在执行的线程在指定的时间内暂停执行,进入阻塞状态,该方法既可以让其他同优 ...

  8. JDK1.8新特性之Stream类初识

    JDK1.8新特性之Stream类初识 import java.util.Arrays; import java.util.List; import java.util.Optional; impor ...

  9. boost container

    Boost Container provides additional advantages: (1) The interface of the containers resemble those o ...

  10. boost bimap

    The library Boost.Bimap is based on Boost.MultiIndex and provides a container that can be used immed ...