本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名原文链接~~~

Hibernate(7)之几种检索方式示例

微信搜索 zze_coding 或扫描 👉 二维码关注我的微信公众号获取更多资源推送:


准备

模型及映射文件

// 班级模型:com.zze.bean.Class
package com.zze.bean;

import java.util.HashSet;
import java.util.Set;

public class Class {
    public Class() {
    }

    public Class(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    private Integer id;
    private String name;

    private Set<Student> students = new HashSet<>();

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Class{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
<!-- 班级映射:com/zze/bean/Class.hbm.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.zze.bean.Class" table="class">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name" length="32"/>
        <set name="students" cascade="save-update">
            <key column="cid"/>
            <one-to-many class="com.zze.bean.Student"/>
        </set>
    </class>
</hibernate-mapping>
<!-- 学生模型:com.zze.bean.Student -->
package com.zze.bean;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

public class Student {
    public Student() {
    }

    public Student(Integer id, String name, Integer age,String gender) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    private Integer id;
    private String name;
    private Integer age;
    private String gender;

    private Class clazz;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Class getClazz() {
        return clazz;
    }

    public void setClazz(Class clazz) {
        this.clazz = clazz;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
<!-- 学生映射:com/zze/bean/Student.hbm.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.zze.bean.Student" table="student">
        <id name="id">
            <generator class="native"/>
        </id>
        <property name="name" length="32"/>
        <property name="age"/>
        <property name="gender"/>
        <many-to-one name="clazz" column="cid" class="com.zze.bean.Class"/>
    </class>
</hibernate-mapping>

全局配置

<!-- hibernate.cfg.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://192.168.208.153:3306/1221</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="current_session_context_class">thread</property>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <mapping resource="com/zze/bean/Class.hbm.xml"></mapping>
        <mapping resource="com/zze/bean/Student.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

工具类

// com.zze.util.HibernateUtil
package com.zze.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    public static final Configuration cfg;
    public static final SessionFactory sf;

    static {
        cfg = new Configuration().configure();
        sf = cfg.buildSessionFactory();
    }

    public static Session openSession() {
        return sf.openSession();
    }

    public static Session getCurrentSession() {
        return sf.getCurrentSession();
    }
}

初始化数据

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Class clazz1 = new Class(null,"软件一班");
Class clazz2 = new Class(null,"软件二班");
Class clazz3 = new Class(null,"汽修一班");
Class clazz4 = new Class(null,"汽修二班");

Student student1 = new Student(null, "张三", 12,"男");
Student student2 = new Student(null, "李四", 13,"女");
Student student3 = new Student(null, "王五", 14,"男");
Student student4 = new Student(null, "赵六", 15,"男");
Student student5 = new Student(null, "吴刚", 39,"男");
Student student6 = new Student(null, "王如花", 30,"女");
Student student7 = new Student(null, "李志静", 49,"女");
Student student8 = new Student(null, "何王天", 30,"男");

clazz1.getStudents().add(student1);
clazz1.getStudents().add(student2);
clazz2.getStudents().add(student3);
clazz2.getStudents().add(student4);
clazz3.getStudents().add(student5);
clazz3.getStudents().add(student6);
clazz4.getStudents().add(student7);
clazz4.getStudents().add(student8);

session.save(clazz1);
session.save(clazz2);
session.save(clazz3);
session.save(clazz4);
transaction.commit();

image.png

几种检索方式

OID 检索

Hibernate 根据对象的 OID(主键)进行检索。

使用 get 方法

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Class clazz = session.get(Class.class, 1);
System.out.println(clazz);
transaction.commit();
/*
Hibernate:
    select
        class0_.id as id1_0_0_,
        class0_.name as name2_0_0_
    from
        class class0_
    where
        class0_.id=?
Class{id=1, name='软件一班'}
 */

使用 load 方法

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Class clazz = session.load(Class.class, 1);
System.out.println(clazz);
transaction.commit();
/*
Hibernate: 
    select
        class0_.id as id1_0_0_,
        class0_.name as name2_0_0_ 
    from
        class class0_ 
    where
        class0_.id=?
Class{id=1, name='软件一班'}
 */

对象导航检索

Hibernate 根据一个已经查询到的对象,获得其关联的对象的一种查询方式。

导航查询

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Class clazz = session.load(Class.class, 1);
System.out.println(clazz);
System.out.println(Arrays.toString(clazz.getStudents().toArray()));
transaction.commit();
/*
Hibernate:
    select
        class0_.id as id1_0_0_,
        class0_.name as name2_0_0_
    from
        class class0_
    where
        class0_.id=?
Class{id=1, name='软件一班'}
Hibernate:
    select
        students0_.cid as cid5_1_0_,
        students0_.id as id1_1_0_,
        students0_.id as id1_1_1_,
        students0_.name as name2_1_1_,
        students0_.age as age3_1_1_,
        students0_.gender as gender4_1_1_,
        students0_.cid as cid5_1_1_
    from
        student students0_
    where
        students0_.cid=?
[Student{id=2, name='张三'}, Student{id=1, name='李四'}]
 */

HQL检索

Hibernate Language Query,Hibernate 本身提供语法支持的一种检索方式。

简单查询 - 查询所有班级

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql  ="from Class";
Query query = session.createQuery(hql);
List<Class> list = query.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        class0_.id as id1_0_,
        class0_.name as name2_0_
    from
        class class0_
[Class{id=1, name='软件一班'}, Class{id=2, name='软件二班'}, Class{id=3, name='汽修一班'}, Class{id=4, name='汽修二班'}]
 */

别名查询

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql  ="select c from Class c";
Query query = session.createQuery(hql);
List<Class> list = query.list();
System.out.println(list);
transaction.commit();
/*
    Hibernate:
        select
            class0_.id as id1_0_,
            class0_.name as name2_0_
        from
            class class0_
    [Class{id=1, name='软件一班'}, Class{id=2, name='软件二班'}, Class{id=3, name='汽修一班'}, Class{id=4, name='汽修二班'}]
 */

排序查询 - 根据年龄排序

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
// 升序
String hql = "from Student order by age";
// 降序
// String hql = "from Student order by age desc";
Query query = session.createQuery(hql);
List<Class> list = query.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        student0_.id as id1_1_,
        student0_.name as name2_1_,
        student0_.age as age3_1_,
        student0_.gender as gender4_1_,
        student0_.cid as cid5_1_
    from
        student student0_
    order by
        student0_.age
[Student{id=2, name='张三'}, Student{id=1, name='李四'}, Student{id=3, name='王五'}, Student{id=4, name='赵六'}, Student{id=6, name='王如花'}, Student{id=8, name='何王天'}, Student{id=5, name='吴刚'}, Student{id=7, name='李志静'}]
 */

条件查询

1、一个条件,查询 name='张三' 的 Student。

Transaction transaction = session.beginTransaction();
// 参数按位置绑定
String hql = "from Student where name = ?";
Query query = session.createQuery(hql);
query.setParameter(0, "张三");
List<Student> list = query.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        student0_.id as id1_1_,
        student0_.name as name2_1_,
        student0_.age as age3_1_,
        student0_.gender as gender4_1_,
        student0_.cid as cid5_1_
    from
        student student0_
    where
        student0_.name=?
[Student{id=2, name='张三'}]
 */

2、多个条件 - 查询 name 中包含 '王'age 大于 18 的 Student。

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "from Student where name like :name and age>:age";
Query query = session.createQuery(hql);
query.setParameter("name", "%王%");
query.setParameter("age", 18);
List<Student> list = query.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        student0_.id as id1_1_,
        student0_.name as name2_1_,
        student0_.age as age3_1_,
        student0_.gender as gender4_1_,
        student0_.cid as cid5_1_
    from
        student student0_
    where
        (
            student0_.name like ?
        )
        and student0_.age>?
[Student{id=6, name='王如花'}, Student{id=8, name='何王天'}]
 */

投影查询

1、查询单个属性,返回 List<Object>

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "select s.name from Student s";
Query query = session.createQuery(hql);
List<Object> list = query.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        student0_.name as col_0_0_
    from
        student student0_
[李四, 张三, 王五, 赵六, 吴刚, 王如花, 李志静, 何王天]
 */

2、查询多个属性,返回 List<Object[]>

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "select s.name,s.age from Student s";
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
for (Object[] objects : list) {
    System.out.println(Arrays.toString(objects));
}
transaction.commit();
/*
Hibernate:
    select
        student0_.name as col_0_0_,
        student0_.age as col_1_0_
    from
        student student0_
[李四, 13]
[张三, 12]
[王五, 14]
[赵六, 15]
[吴刚, 39]
[王如花, 30]
[李志静, 49]
[何王天, 30]
 */

3、查询多个属性,返回 List<Class>

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
/*
需要让模型提供对应构造:
    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
 */
String hql = "select new Student(name,age) from Student";
Query query = session.createQuery(hql);
List<Student> list = query.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        student0_.name as col_0_0_,
        student0_.age as col_1_0_
    from
        student student0_
[Student{id=null, name='李四'}, Student{id=null, name='张三'}, Student{id=null, name='王五'}, Student{id=null, name='赵六'}, Student{id=null, name='吴刚'}, Student{id=null, name='王如花'}, Student{id=null, name='李志静'}, Student{id=null, name='何王天'}]
 */

分页查询

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "from Student";
Query query = session.createQuery(hql);
query.setFirstResult(0); // 起始行索引
query.setMaxResults(3); // 每页条数
List<Student> list = query.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        student0_.id as id1_1_,
        student0_.name as name2_1_,
        student0_.age as age3_1_,
        student0_.gender as gender4_1_,
        student0_.cid as cid5_1_
    from
        student student0_ limit ?
[Student{id=1, name='李四'}, Student{id=2, name='张三'}, Student{id=3, name='王五'}]

Process finished with exit code 0
 */

聚合查询

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
// 聚合函数使用 count max min avg sum
String hql = "select count(1) from Student";
Query query = session.createQuery(hql);
Object o = query.uniqueResult();
System.out.println(o.getClass());
System.out.println(o);
transaction.commit();
/*
Hibernate:
    select
        count(1) as col_0_0_
    from
        student student0_
class java.lang.Long
8
 */

分组查询

根据 gender 分组,查询每个 gender 的对应数据条数,返回 List<Object[]>

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "select gender,count(1) from Student group by gender";
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
for (Object[] objects : list) {
    System.out.println(Arrays.toString(objects));
}
transaction.commit();
/*
Hibernate:
    select
        student0_.gender as col_0_0_,
        count(1) as col_1_0_
    from
        student student0_
    group by
        student0_.gender
[女, 3]
[男, 5]
 */

普通内连接

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "from Student c join c.clazz";
Query query = session.createQuery(hql);
List<Object[]> list = query.list();
for (Object[] objects : list) {
    System.out.println(Arrays.toString(objects));
}
transaction.commit();
/*
Hibernate:
    select
        student0_.id as id1_1_0_,
        class1_.id as id1_0_1_,
        student0_.name as name2_1_0_,
        student0_.age as age3_1_0_,
        student0_.gender as gender4_1_0_,
        student0_.cid as cid5_1_0_,
        class1_.name as name2_0_1_
    from
        student student0_
    inner join
        class class1_
            on student0_.cid=class1_.id
[Student{id=1, name='李四'}, Class{id=1, name='软件一班'}]
[Student{id=2, name='张三'}, Class{id=1, name='软件一班'}]
[Student{id=3, name='王五'}, Class{id=2, name='软件二班'}]
[Student{id=4, name='赵六'}, Class{id=2, name='软件二班'}]
[Student{id=5, name='吴刚'}, Class{id=3, name='汽修一班'}]
[Student{id=6, name='王如花'}, Class{id=3, name='汽修一班'}]
[Student{id=7, name='李志静'}, Class{id=4, name='汽修二班'}]
[Student{id=8, name='何王天'}, Class{id=4, name='汽修二班'}]
 */

迫切内连接

迫切内连接: 其实就是在普通的内连接 inner join 后添加关键字 fetch,将关联表数据封装到查询对象的属性中。

1、查询所有学生及其班级。

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "from Student c join fetch c.clazz";
Query query = session.createQuery(hql);
List<Student> list = query.list();
for (Student student : list) {
    System.out.println(String.format("%s %s", student, student.getClazz()));
}
transaction.commit();
/*
Hibernate:
    select
        student0_.id as id1_1_0_,
        class1_.id as id1_0_1_,
        student0_.name as name2_1_0_,
        student0_.age as age3_1_0_,
        student0_.gender as gender4_1_0_,
        student0_.cid as cid5_1_0_,
        class1_.name as name2_0_1_
    from
        student student0_
    inner join
        class class1_
            on student0_.cid=class1_.id
Student{id=1, name='李四'} Class{id=1, name='软件一班'}
Student{id=2, name='张三'} Class{id=1, name='软件一班'}
Student{id=3, name='王五'} Class{id=2, name='软件二班'}
Student{id=4, name='赵六'} Class{id=2, name='软件二班'}
Student{id=5, name='吴刚'} Class{id=3, name='汽修一班'}
Student{id=6, name='王如花'} Class{id=3, name='汽修一班'}
Student{id=7, name='李志静'} Class{id=4, name='汽修二班'}
Student{id=8, name='何王天'} Class{id=4, name='汽修二班'}
 */

2、查询所有班级以及属于该班级的学生。

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String hql = "select distinct c from Class c join fetch c.students";
Query query = session.createQuery(hql);
List<Class> list = query.list();
for (Class clazz : list) {
    System.out.println(String.format("%s %s", clazz, clazz.getStudents()));
}
transaction.commit();
/*
Class{id=1, name='软件一班'} [Student{id=2, name='张三'}, Student{id=1, name='李四'}]
Class{id=2, name='软件二班'} [Student{id=4, name='赵六'}, Student{id=3, name='王五'}]
Class{id=3, name='汽修一班'} [Student{id=5, name='吴刚'}, Student{id=6, name='王如花'}]
Class{id=4, name='汽修二班'} [Student{id=7, name='李志静'}, Student{id=8, name='何王天'}]
 */

QBC检索

Query By Criteria,条件查询,是一种更加面向对象化的查询方式。

简单查询

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Class.class);
List<Class> list = criteria.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        this_.id as id1_0_0_,
        this_.name as name2_0_0_
    from
        class this_
[Class{id=1, name='软件一班'}, Class{id=2, name='软件二班'}, Class{id=3, name='汽修一班'}, Class{id=4, name='汽修二班'}]
 */

排序查询

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Class.class);
// 升序
criteria.addOrder(Order.asc("id"));
// 降序
// criteria.addOrder(Order.desc("id"));
List<Class> list = criteria.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        this_.id as id1_0_0_,
        this_.name as name2_0_0_
    from
        class this_
    order by
        this_.id asc
[Class{id=1, name='软件一班'}, Class{id=2, name='软件二班'}, Class{id=3, name='汽修一班'}, Class{id=4, name='汽修二班'}]
 */

分页查询

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Student.class);
criteria.setFirstResult(0); // 数据起始索引
criteria.setMaxResults(2); // 每页数据条数
List<Student> list = criteria.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        this_.id as id1_1_0_,
        this_.name as name2_1_0_,
        this_.age as age3_1_0_,
        this_.gender as gender4_1_0_,
        this_.cid as cid5_1_0_
    from
        student this_ limit ?
[Student{id=1, name='李四'}, Student{id=2, name='张三'}]
 */

条件查询

1、简单 and 条件查询 - 查询 name 包含 '王'age>10 的学生。

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Student.class);
// 默认多个 criteria.add 的条件是用 and 连接
criteria.add(Restrictions.like("name", "%王%"));
criteria.add(Restrictions.gt("age", 10));
List<Student> list = criteria.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        this_.id as id1_1_0_,
        this_.name as name2_1_0_,
        this_.age as age3_1_0_,
        this_.gender as gender4_1_0_,
        this_.cid as cid5_1_0_
    from
        student this_
    where
        this_.name like ?
        and this_.age>?
[Student{id=3, name='王五'}, Student{id=6, name='王如花'}, Student{id=8, name='何王天'}]
 */

2、简单 or 条件查询 - 查询 name 包含 '王'name 包含 '张' 的学生。

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Student.class);
// or 条件可以通过 Restrictions.or 方法实现
criteria.add(Restrictions.or(Restrictions.like("name", "%王%"), Restrictions.like("name", "%张%")));
List<Student> list = criteria.list();
System.out.println(list);
transaction.commit();

/*
Hibernate:
    select
        this_.id as id1_1_0_,
        this_.name as name2_1_0_,
        this_.age as age3_1_0_,
        this_.gender as gender4_1_0_,
        this_.cid as cid5_1_0_
    from
        student this_
    where
        (
            this_.name like ?
            or this_.name like ?
        )
[Student{id=2, name='张三'}, Student{id=3, name='王五'}, Student{id=6, name='王如花'}, Student{id=8, name='何王天'}]
 */

3、复杂 andor 查询 - 查询 (name 包含 '王'age>10) 或 name 包含 '张' 的学生。

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Student.class);
// 通过 conjunction.add 添加的条件是 and 连接
Conjunction conjunction = Restrictions.conjunction();
conjunction.add(Restrictions.like("name", "%王%"));
conjunction.add(Restrictions.gt("age", 10));
// 通过 disjunction.add 添加的条件是 or 连接
Disjunction disjunction = Restrictions.disjunction();
disjunction.add(conjunction);
disjunction.add(Restrictions.like("name", "%张%"));
criteria.add(disjunction);
List<Student> list = criteria.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        this_.id as id1_1_0_,
        this_.name as name2_1_0_,
        this_.age as age3_1_0_,
        this_.gender as gender4_1_0_,
        this_.cid as cid5_1_0_
    from
        student this_
    where
        (
            (
                this_.name like ?
                and this_.age>?
            )
            or this_.name like ?
        )
[Student{id=2, name='张三'}, Student{id=3, name='王五'}, Student{id=6, name='王如花'}, Student{id=8, name='何王天'}]
 */

聚合及分组统计查询

统计男女人数及最大年龄。

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = session.createCriteria(Student.class);
/*
criteria :
    add : 普通条件,where
    addOrder : 排序
    setProjection : 聚合函数和 group by having
 */
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("gender"));
projectionList.add(Projections.rowCount());
projectionList.add(Projections.max("age"));
criteria.setProjection(projectionList);

List<Object[]> list = criteria.list();
for (Object[] objects : list) {
    System.out.println(Arrays.toString(objects));
}
transaction.commit();
/*
Hibernate:
    select
        this_.gender as y0_,
        count(*) as y1_,
        max(this_.age) as y2_
    from
        student this_
    group by
        this_.gender
[女, 3, 49]
[男, 5, 39]
 */

离线条件查询

查询 name 包含 '一' 的班级。

DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Class.class);
detachedCriteria.add(Restrictions.like("name", "%一%"));
Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
Criteria criteria = detachedCriteria.getExecutableCriteria(session);
List<Class> list = criteria.list();
System.out.println(list);
transaction.commit();
/*
Hibernate:
    select
        this_.id as id1_0_0_,
        this_.name as name2_0_0_
    from
        class this_
    where
        this_.name like ?
[Class{id=1, name='软件一班'}, Class{id=3, name='汽修一班'}]
 */

SQL 检索

Hibernate 支持的原生 SQL 查询。

SQL 查询返回 List<Object>

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String sql = "select * from class";
SQLQuery sqlQuery = session.createSQLQuery(sql);
List<Object[]> list = sqlQuery.list();
for (Object[] objects : list) {
    System.out.println(Arrays.toString(objects));
}
transaction.commit();
/*
Hibernate:
    select
        *
    from
        class
[1, 软件一班]
[2, 软件二班]
[3, 汽修一班]
[4, 汽修二班]
 */

SQL 查询返回 List<Class>

Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
String sql = "select * from class";
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity(Class.class);
List<Class> list = sqlQuery.list();
for (Class clazz : list) {
    System.out.println(clazz);
}
transaction.commit();
/*
Hibernate:
    select
        *
    from
        class
Class{id=1, name='软件一班'}
Class{id=2, name='软件二班'}
Class{id=3, name='汽修一班'}
Class{id=4, name='汽修二班'}
 */
# Hibernate  

如果这篇文章对您有帮助,可点击下方链接分享给你的朋友们😋,如果遇到问题欢迎评论、留言~~~😇

评论

公众号:zze_coding

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×