Hibernate学习10——Hibernate 查询方式

本章主要是以查询Student的例子:

Student.java:

package com.cy.model;

public class Student {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

}

Student.hbm.xml:

<hibernate-mapping package="com.cy.model">

    <class name="Student" table="t_student">
        <id name="id" column="stuId">
            <generator class="native"></generator>
        </id>
        <property name="name" column="stuName"></property>
        <property name="age" column="stuAge"></property>
    </class>

</hibernate-mapping>

数据库中student数据:

第一节:Hibernate 查询方式简介                                    

导航对象图是说from Student s where s.name = xxx and s.age = xxx这样可以对象.属性这样子;

OID查询方式:比如Session.get(Student.class, 1);根据ID查询这样子;

第二节:本地SQL 查询方式                                  

/**
     * 本地sql查询,不带参数
     */
    @Test
    public void testSQLQuery(){
        String sql = "select * from t_student";
        Query query = session.createSQLQuery(sql).addEntity(Student.class);    //查询student,绑定Student实体
        List<Student> studentList = query.list();
        for(Student s: studentList){
            System.out.println(s);
        }

        /**
         *  Hibernate: select * from t_student
            Student [id=1, name=张三, age=10]
            Student [id=2, name=李四, age=15]
            Student [id=3, name=王五, age=13]
         */
    }

    /**
     * 本地sql查询,带参数
     * 查询姓名张开头,且10岁
     */
    @Test
    public void testSQLQuery2(){
        String sql = "select * from t_student where stuName like :stuName and stuAge = :stuAge";
        Query query = session.createSQLQuery(sql).addEntity(Student.class);    //查询student,绑定Student实体
        query.setString("stuName", "张%");
        query.setInteger("stuAge", 10);
        List<Student> studentList = query.list();
        for(Student s: studentList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select * from t_student where stuName like ? and stuAge = ?
            Student [id=1, name=张三, age=10]
         */
    }

第三节:HQL 查询方式                                        

package com.cy.service;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.cy.model.Student;
import com.cy.util.HibernateUtil;

public class StudentTest {

    private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
    private Session session;

    @Before
    public void setUp() throws Exception {
        session=sessionFactory.openSession();
        session.beginTransaction();
    }

    @After
    public void tearDown() throws Exception {
         session.getTransaction().commit();
         session.close();
    }

    /**
     * 本地sql查询,不带参数
     */
    @Test
    public void testSQLQuery(){
        String sql = "select * from t_student";
        Query query = session.createSQLQuery(sql).addEntity(Student.class);    //查询student,绑定Student实体
        List<Student> studentList = query.list();
        for(Student s: studentList){
            System.out.println(s);
        }

        /**
         *  Hibernate: select * from t_student
            Student [id=1, name=张三, age=10]
            Student [id=2, name=李四, age=15]
            Student [id=3, name=王五, age=13]
         */
    }

    /**
     * 本地sql查询,带参数
     * 查询姓名张开头,且10岁
     */
    @Test
    public void testSQLQuery2(){
        String sql = "select * from t_student where stuName like :stuName and stuAge = :stuAge";
        Query query = session.createSQLQuery(sql).addEntity(Student.class);    //查询student,绑定Student实体
        query.setString("stuName", "张%");
        query.setInteger("stuAge", 10);
        List<Student> studentList = query.list();
        for(Student s: studentList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select * from t_student where stuName like ? and stuAge = ?
            Student [id=1, name=张三, age=10]
         */
    }

    /**
     * HQL查询
     */
    @Test
    public void testHQLQuery(){
        String hql = "from Student";
        Query query = session.createQuery(hql);
        List<Student> studentList = query.list();
        for(Student s : studentList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select student0_.stuId as stuId1_0_, student0_.stuName as stuName2_0_, student0_.stuAge as stuAge3_0_ from t_student student0_
            Student [id=1, name=张三, age=10]
            Student [id=2, name=李四, age=15]
            Student [id=3, name=王五, age=13]
         */
    }

    /**
     * HQL 带条件查询
     */
    @Test
    public void testHQLQuery2(){
        String hql = "from Student where name like :stuName and age = :stuAge ";
        Query query = session.createQuery(hql);
        query.setString("stuName", "张%");
        query.setInteger("stuAge", 10);
        List<Student> studentList = query.list();
        for(Student s : studentList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select student0_.stuId as stuId1_0_, student0_.stuName as stuName2_0_, student0_.stuAge as stuAge3_0_ from t_student student0_ where (student0_.stuName like ?) and student0_.stuAge=?
            Student [id=1, name=张三, age=10]
         */
    }

    /**
     * HQL 使用别名
     * from Student as s
     * 或者
     * from Student s
     */
    @Test
    public void testHQLQuery3(){
        String hql="from Student as s where s.name like :stuName and s.age=:stuAge";
        Query query=session.createQuery(hql);
        query.setString("stuName", "张%");
        query.setInteger("stuAge", 10);
        List<Student> studentList= query.list();
        for(Student s : studentList){
            System.out.println(s);
        }
    }

    /**
     * HQL查询 对结果排序
     * 按照年龄降序排列
     */
    @Test
    public void testHQLQuery4(){
        String hql = "from Student order by age desc";
        Query query = session.createQuery(hql);
        List<Student> studentList = query.list();
        for(Student s : studentList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select student0_.stuId as stuId1_0_, student0_.stuName as stuName2_0_, student0_.stuAge as stuAge3_0_ from t_student student0_ order by student0_.stuAge desc
            Student [id=2, name=李四, age=15]
            Student [id=3, name=王五, age=13]
            Student [id=1, name=张三, age=10]
         */
    }

    /**
     * HQL查询  分页查询
     */
    @Test
    public void testHQLQuery5(){
        String hql="from Student";
        Query query=session.createQuery(hql);
        //第1条记录开始,取2条;
        query.setFirstResult(1);
        query.setMaxResults(2);
        List<Student> studentList = query.list();
        for(Student s : studentList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select student0_.stuId as stuId1_0_, student0_.stuName as stuName2_0_, student0_.stuAge as stuAge3_0_ from t_student student0_ limit ?, ?
            Student [id=2, name=李四, age=15]
            Student [id=3, name=王五, age=13]
         */
    }

    /**
     * HQL查询  查询单个对象
     * 查询出一条记录,完全能确定是一条记录,这里就不是list了,uniqueResult
     * 比如查询总记录数,就可以用uniqueResult
     */
    @Test
    public void testHQLQuery6() {
        String hql="from Student";
        Query query=session.createQuery(hql);
        query.setFirstResult(1);
        query.setMaxResults(1);
        Student s = (Student) query.uniqueResult();
        System.out.println(s);    

        /*
         *  Hibernate: select student0_.stuId as stuId1_0_, student0_.stuName as stuName2_0_, student0_.stuAge as stuAge3_0_ from t_student student0_ limit ?, ?
            Student [id=2, name=李四, age=15]
         */
    }

    /**
     * HQL  链式写法
     */
    @SuppressWarnings("unchecked")
    @Test
    public void testHQLQuery7() {
        String hql = "from Student s where s.name like :stuName and s.age = :stuAge";
        List<Student> studentList = session.createQuery(hql)
                                           .setString("stuName", "李%")
                                           .setInteger("stuAge", 15)
                                           .list();
        for(Student s : studentList){
            System.out.println(s);
        }

        /*
         * Student [id=2, name=李四, age=15]
         */
    }

}

第四节:QBC 查询方式                                              

package com.cy.service;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.cy.model.Student;
import com.cy.util.HibernateUtil;

public class StudentTest {

    private SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
    private Session session;

    @Before
    public void setUp() throws Exception {
        session=sessionFactory.openSession();
        session.beginTransaction();
    }

    @After
    public void tearDown() throws Exception {
         session.getTransaction().commit();
         session.close();
    }

    /**
     * QBC查询
     */
    @Test
    public void testQBCQuery(){
        Criteria criteria = session.createCriteria(Student.class);
        List<Student> stuList = criteria.list();
        for(Student s : stuList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select this_.stuId as stuId1_0_0_, this_.stuName as stuName2_0_0_, this_.stuAge as stuAge3_0_0_ from t_student this_
            Student [id=1, name=张三, age=10]
            Student [id=2, name=李四, age=15]
            Student [id=3, name=王五, age=13]
         */
    }

    /**
     * QBC 带条件查询
     */
    @Test
    public void testQBCQuery2(){
        Criteria criteria = session.createCriteria(Student.class);
        Criterion c1 = Restrictions.like("name", "李%");
        Criterion c2 = Restrictions.eq("age", 15);
        criteria.add(c1);
        criteria.add(c2);
        List<Student> stuList = criteria.list();
        for(Student s : stuList){
            System.out.println(s);
        }
        /*
         *  Hibernate: select this_.stuId as stuId1_0_0_, this_.stuName as stuName2_0_0_, this_.stuAge as stuAge3_0_0_ from t_student this_ where this_.stuName like ? and this_.stuAge=?
            Student [id=2, name=李四, age=15]
         */
    }

    /**
     * QBC 对结果排序
     */
    @Test
    public void testQBCQuery3(){
        Criteria criteria = session.createCriteria(Student.class);
        criteria.addOrder(Order.desc("age"));
        List<Student> stuList = criteria.list();
        for(Student s : stuList){
            System.out.println(s);
        }

        /*
         *  Student [id=2, name=李四, age=15]
            Student [id=3, name=王五, age=13]
            Student [id=1, name=张三, age=10]
         */
    }

    /**
     * QBC 分页查询
     */
    @Test
    public void testQBCQuery4(){
        Criteria criteria = session.createCriteria(Student.class);
        criteria.setFirstResult(0);    //从第0条记录开始
        criteria.setMaxResults(2);    //查询2条
        List<Student> stuList = criteria.list();
        for(Student s : stuList){
            System.out.println(s);
        }

        /*
         *  Hibernate: select this_.stuId as stuId1_0_0_, this_.stuName as stuName2_0_0_, this_.stuAge as stuAge3_0_0_ from t_student this_ limit ?
            Student [id=1, name=张三, age=10]
            Student [id=2, name=李四, age=15]
         */
    }

    /**
     * QBC 查询单个对象
     * 因为这里只取一条记录,uniqueResult
     */
    @Test
    public void testQBCQuery5(){
        Criteria criteria = session.createCriteria(Student.class);
        criteria.setFirstResult(2);
        criteria.setMaxResults(1);
        Student    s = (Student) criteria.uniqueResult();
        System.out.println(s);

        /*
         *  Hibernate: select this_.stuId as stuId1_0_0_, this_.stuName as stuName2_0_0_, this_.stuAge as stuAge3_0_0_ from t_student this_ limit ?, ?
            Student [id=3, name=王五, age=13]
         */
    }

    /**
     * QBC 链式写法
     */
    @SuppressWarnings("unchecked")
    @Test
    public void testQBCQuery6(){
        Criterion c1 = Restrictions.like("name", "李%");
        Criterion c2 = Restrictions.eq("age", 15);
        List<Student> stuList = session.createCriteria(Student.class)
                                       .add(c1)
                                       .add(c2)
                                       .list();
        for(Student s : stuList){
            System.out.println(s);
        }
    }

}

时间: 2024-10-15 03:31:02

Hibernate学习10——Hibernate 查询方式的相关文章

Hibernate学习笔记--------4.查询

一.Get/Load Get方法是立即检索,而load是延迟检索,他们都是根据主键进行查询.在<class>标签中,若把lazy属性改为false,load方法就会立即检索,class中的lazy属性仅对load方法有效.在使用load时,当数据库没有找到数据时,会有ObjectNotFoundException,异常. 1 public void LazyTest() { 2 //lazy 改为false或者true,查看打印sql的时机 3 Tb_User u = session.load

hibernate的三种查询方式

hibernate的查询方式常见的主要分为三种: HQL, QBC, 以及使用原生SQL查询(Session的查询) 1)Query的查询:使用HQL语句或SQL语句完成查询 2)Criteria的查询:通过方法和类中属性的关系,来设置查询条件,完成查询. 3)Session的查询:按主键查询查询,方法为get或load 一.HQL查询 ? HQL(Hibernate Query Language)提供了丰富灵活的查询方式,使用HQL进行查询也是Hibernate官方推荐使用的查询方式. ? H

Hibernate之HQL检索(查询)方式

HQL(Hibernate Query Language)是面向对象的查询语言,与SQL非常相似.在Hibernate中,HQL是使用最广泛的检索方式. 具有下面经常使用功能: (1)在查询语句中,能够设定各种条件 (2)支持检出对象的部分属性,就是SQL语句中不用*,而是查询我们想查询的对象 (3)支持连接查询 (4)支持分页查询 (5)支持子查询 (6)支持动态绑定參数 (7)支持分组查询,能够用having,group by (8)提供分组函数(内置聚集函数,sum(),count(),a

Hibernate的几种查询方式-HQL,QBC,QBE,离线查询,复合查询,分页查询

HQL查询方式 这一种我最常用,也是最喜欢用的,因为它写起来灵活直观,而且与所熟悉的SQL的语法差不太多.条件查询.分页查询.连接查询.嵌套查询,写起来与SQL语法基本一致,唯一不同的就是把表名换成了类或者对象.其它的,包括一些查询函数(count(),sum()等).查询条件的设定等,全都跟SQL语法一样. 示例: Session session = SessionFactory.getCurrentSession(); User user = null; Transaction ts = s

hibernate学习---单表查询

我们都知道SQL是非常强大的,为什么这么说呢?相信学过数据库原理的同学们都深有体会,SQL语句变化无穷,好毫不夸张的说可以实现任意符合我们需要的数据库操作,既然前面讲到Hibernate非常强大,所以Hibernate也是能够实现SQL的一切数据库操作. 在SQL中,单表查询是最常用的语句,同理Hibernate最常用到的也是查询语句,所以今天就来讲讲Hibernate的单表查询: 今天要将的内容分以下几点: 查询所有 查询结果排序 为查询参数动态赋值 分页查询 模糊查询 唯一性查询 聚合函数查

3、Hibenrate中HQL的10中查询方式

二.具体事例如下: 2.0 编写如下sql语句 1 create table teacher(tid number not null primary key,tname varchar2(20)); 2 create sequence seq_teacher; 3 insert into teacher values(seq_teacher.nextval,'holly'); 4 insert into teacher values(seq_teacher.nextval,'石头'); 5 co

Hibernate学习0.Hibernate入门

Hibernate是什么 面向java环境的对象/关系数据库映射工具. 1.开源的持久层框架. 2.ORM(Object/Relational Mapping)映射工具,建立面向对象的域模型和关系数据模型之间的映射. 3.连接java应用和数据库的中间件. 4.对JDBC进行封装,负责java对象的持久化. 5.在分层结构中处于持久化层,封装对数据库的访问细节,使业务逻辑层更专注于实现业务逻辑 Hibernate作用 Hibernate是Java应用和关系数据库之间的桥梁,它负责Java对象和关

Hibernate学习之Hibernate流程

Hibernate的核心组件 在基于MVC设计模式的JAVA WEB应用中,Hibernate可以作为模型层/数据访问层.它通过配置文件(hibernate.properties或hibernate.cfg.xml)和映射文件(***.hbm.xml)把JAVA对象或PO(Persistent Object,持久化对象)映射到数据库中的数据库,然后通过操作PO,对数据表中的数据进行增,删,改,查等操作.除配置文件,映射文件和持久化类外,Hibernate的核心组件包括以下几部分:a)Config

Hibernate学习之hql查询语句

*  页面上数据的字段和数据库中字段差不多,这个时候,采用迫切连接  结构比较好,如果页面上的字段很少,要按照需求加载数据,采用带构造函数的select查询 实例讲解:转自:http://www.cnblogs.com/xiaoluo501395377/p/3376256.html 在这里通过定义了三个类,Special.Classroom.Student来做测试,Special与Classroom是一对多,Classroom与Student是一对多的关系,这里仅仅贴出这三个bean的属性代码: