`

Hibernate查询方式

阅读更多
1) Hibernate查询方式简介

新建项目Hibernate10


1.1) 导航对象图查询方式

1.2) OID查询方式

1.3) 本地SQL查询方式

1.4) HQL查询方式

1.5) QBC查询方式(Query By Criteria)

2) 本地SQL查询方式

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="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate4</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <!-- 方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 控制台显示SQL -->
        <property name="show_sql">true</property>
        <!-- 自动更新表结构 -->
        <property name="hbm2ddl.auto">update</property>
        <!-- Mapper -->
        <mapping resource="com/andrew/model/Student.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

HibernateUtil.java

package com.andrew.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        // 1. 实例化配置文件
        Configuration configuration = new Configuration().configure();
        // 2. 实例化服务登记
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        // 3. 获取Session工厂
        return configuration.buildSessionFactory(serviceRegistry);
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Student.java

package com.andrew.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

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.andrew.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>

insert into t_student values(1, '张三', 10);
insert into t_student values(2, '李四', 15);
insert into t_student values(3, '王五', 13);

StudentTest.java

package com.andrew.service;
import java.util.Iterator;
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.andrew.model.Student;
import com.andrew.util.HibernateUtil;
public class StudentTest {
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    private Session session;
    @Before
    public void setUp() throws Exception {
        session = sessionFactory.openSession(); // 1. 生成一个session
        session.beginTransaction(); // 2. 开启事务
    }
    @After
    public void tearDown() throws Exception {
        session.getTransaction().commit(); // 3. 提交事务
        session.close(); // 4. 关闭session
    }
    @Test
    public void testSQLQuery() {
        String sql = "select * from t_student";
        Query query = session.createSQLQuery(sql).addEntity(Student.class);
        List studentList = query.list();
        Iterator it = studentList.iterator();
        while (it.hasNext()) {
            Student s = (Student)it.next();
            System.out.println(s);
        }        
    }
    @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);
        query.setString("stuName", "张%");
        query.setInteger("stuAge", 10);
        List studentList = query.list();
        Iterator it=studentList.iterator();
        while (it.hasNext()) {
            Student s = (Student)it.next();
            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]
运行结果:
Hibernate: select * from t_student where stuName like ? and stuAge=?
Student [id=1, name=张三, age=10]


3) HQL查询方式

HQL(Hibernate Query Language)是面向对象的查询语言;是使用最广的一种查询方式;


3.1) 普通查询

@Test
public void testHQLQuery() {
    String hql = "from Student";
    Query query = session.createQuery(hql);
    List<Student> studentList = (List<Student>)query.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


3.2) 带条件查询

@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 = (List<Student>)query.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


3.3) 使用别名

@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 = (List<Student>)query.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


3.4) 对结果排序

@Test
public void testHQLQuery4() {
    String hql = "from Student order by age desc";
    Query query = session.createQuery(hql);
    List<Student> studentList = (List<Student>)query.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


3.5) 分页查询

@Test
public void testHQLQuery5() {
    String hql = "from Student";
    Query query = session.createQuery(hql);
    query.setFirstResult(1);
    query.setMaxResults(2);
    List<Student> studentList = (List<Student>)query.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


3.6) 查询单个对象

@Test
public void testHQLQuery6() {
    String hql = "from Student";
    Query query = session.createQuery(hql);
    query.setFirstResult(1);
    query.setMaxResults(1);
    Student student = (Student)query.uniqueResult();
    System.out.println(student);    
}

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]


3.7) 链式写法

@Test
public void testHQLQuery7() {
    String hql = "from Student as s where s.name like :stuName and s.age=:stuAge";
    Query query = session.createQuery(hql);
    List<Student> studentList = (List<Student>)query
            .setString("stuName", "张%")
            .setInteger("stuAge", 10)
            .list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


4) QBC 查询方式

QBC查询方式(Query By Criteria)是用一套接口来实现的查询方式;


4.1) 普通查询

@Test
public void testQBCQuery1() {
    Criteria criteria = session.createCriteria(Student.class);
    List<Student> studentList = criteria.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


4.2) 带条件查询

@Test
public void testQBCQuery2(){
    Criteria criteria = session.createCriteria(Student.class);
    Criterion c1 = Restrictions.like("name", "张%");
    Criterion c2 = Restrictions.eq("age", 10);
    criteria.add(c1);
    criteria.add(c2);
    List<Student> studentList = criteria.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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=1, name=张三, age=10]


4.3) 对结果排序

@Test
public void testQBCQuery3() {
    Criteria criteria = session.createCriteria(Student.class);
    criteria.addOrder(Order.desc("age"));
    List<Student> studentList = criteria.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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_ order by this_.stuAge desc
Student [id=2, name=李四, age=15]
Student [id=3, name=王五, age=13]
Student [id=1, name=张三, age=10]


4.4) 分页查询

@Test
public void testQBCQuery4() {
    Criteria criteria = session.createCriteria(Student.class);
    criteria.setFirstResult(2);
    criteria.setMaxResults(2);
    List<Student> studentList = criteria.list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]


4.5) 查询单个对象

@Test
public void testQBCQuery5() {
    Criteria criteria = session.createCriteria(Student.class);
    criteria.setFirstResult(2);
    criteria.setMaxResults(1);
    Student student = (Student)criteria.uniqueResult();
    System.out.println(student);
}

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]


4.6) 链式写法

@Test
public void testQBCQuery6() {
    Criteria criteria = session.createCriteria(Student.class);
    List<Student> studentList = criteria
            .setFirstResult(0)
            .setMaxResults(2)
            .list();
    Iterator it = studentList.iterator();
    while (it.hasNext()) {
        Student s = (Student)it.next();
        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]
分享到:
评论

相关推荐

    Hibernate查询方式代码示例

    **Hibernate查询方式详解** 在Java世界中,Hibernate作为一款强大的对象关系映射(ORM)框架,极大地简化了数据库操作。本教程将深入探讨Hibernate 3.x版本中的查询方式,包括基本查询、HQL(Hibernate Query ...

    Hibernate的查询方式

    ### Hibernate的查询方式详解 #### 引言 Hibernate作为Java领域中最流行的ORM(Object-Relational Mapping)框架之一,提供了一系列高效、灵活的查询机制,旨在桥接对象模型与关系数据库之间的鸿沟。本文将深入...

    hibernate的查询方式介绍和hibernate的批处理和连接池配置hibernate

    ### Hibernate 查询方式与批处理及连接池配置详解 #### 一、Hibernate 查询方式介绍 Hibernate 是一款优秀的 ORM(对象关系映射)框架,它能够极大地简化数据库操作,并提供多种查询方式来满足不同的业务需求。 #...

    Hibernate学习笔记和资料

    hibernate概述,hibernate入门Demo,hibernate配置文件详解(全局配置,实体类映射配置),配置...hibernate查询方式概述,HQL查询,QBC查询,分页,结果集封装方式 ,高级查询 查询的优化,一级缓存,二级缓存,批量查询,注解方式

    通用的hibernate查询

    【hibernate查询详解】 Hibernate,作为一款强大的Java对象关系映射(ORM)框架,极大地简化了数据库操作。它允许开发者使用面向对象的...理解并熟练掌握这些查询方式,将有助于我们在Java开发中更好地运用Hibernate。

    hibernate中的查询方式

    ### Hibernate中的查询方式详解 #### 一、HQL查询(Hibernate Query Language) HQL是Hibernate提供的面向对象的查询语言,其语法与SQL相似但并非完全相同。HQL的一个显著优势在于它具有很好的跨数据库能力,这...

    hibernate面试题2

    9. **Hibernate查询方式**: - **SQL**:直接执行SQL查询。 - **Criteria API**:面向对象的查询方式。 - **HQL(Hibernate Query Language)**:面向对象的查询语言,支持属性、参数、关联、分页和统计函数查询...

    Hibernate连表查询 Hibernate连表查询

    根据提供的文件信息,我们可以深入探讨Hibernate中的连表查询方法及其应用。下面将详细介绍与标题、描述及部分代码相关的几个核心知识点: ### Hibernate 连表查询基础 Hibernate 是一个开源的对象关系映射(ORM)...

    Hibernate_query查询数据表中的一个字段.

    无论哪种查询方式,最后都会返回一个结果列表,你可以遍历这个列表来获取并处理查询到的`username`字段的值。 总结,Hibernate提供多种方式查询数据表中的字段,包括HQL、Criteria API和DetachedCriteria,选择合适...

    三种查询方式跟踪Hibernate源码

    本文将详细阐述通过三种查询方式跟踪Hibernate源码的方法,帮助开发者更好地掌握其工作原理。 首先,我们来看第一种查询方式:HQL(Hibernate Query Language)查询。HQL是Hibernate专有的SQL方言,允许开发者以...

    struts+hibernate查询所有记录

    ### Struts+Hibernate查询所有记录 #### 一、概述 在Java Web开发中,Struts与Hibernate是非常流行的框架组合,用于构建复杂的企业级应用。本文将详细介绍如何利用Struts和Hibernate来实现对Oracle数据库中所有...

    hibernate多表联合查询

    在Hibernate中,可以使用以下几种方式来实现多表联合查询: - **HQL (Hibernate Query Language)** - **Criteria API** - **Native SQL** 本文将重点介绍如何使用HQL和Native SQL来实现多表联合查询。 #### 三、...

    Hibernate查询练习小例子

    利用MYSQL数据库提供的样例数据库world建立的查询小例子。已经建立好了数据库对应的...本项目主要是为了练习使用Hibernate查询数据库。如果有什么问题可以发站内信或者邮件asddf14@hotmail.com。我会尽量解答一下~~~

    hibernate查询详解

    hibernate查询详解 在Java开发中,Hibernate作为一款强大的ORM(Object-Relational Mapping)框架,极大地简化了数据库操作。本文将详细介绍Hibernate的五种查询方式,包括HQL查询、Criteria方法、动态查询...

    Hibernate查询语言HQL.PPT

    4. 使用 Hibernate 条件 API:提供了类型安全的面向对象的方式执行查询。 5. 使用本地 SQL 查询:Hibernate 只关心把 JDBC 结果集映射到持久对象图。 使用 HQL 的优点: * HQL 是一种面向对象的查询语言,易于学习...

    hibernate

    **六、Hibernate 查询方式** 1. **HQL**: Hibernate 专有的查询语言,类似SQL,但操作的是对象。 2. **Criteria API**: 动态构建查询条件,更加面向对象的查询方式。 3. **Native SQL**: 直接使用原生SQL进行查询,...

    六种方式实现hibernate查询

    六种方式实现Hibernate查询 Hibernate是一个功能强大的持久层框架,它提供了多种方式来查询数据库。下面我们将详细介绍六种方式实现Hibernate查询。 HQL查询 HQL(Hibernate Query Language)是Hibernate自己的...

    hibernate里面的 两种查询

    Hibernate提供了两种主要的查询方式:离线查询(Criteria API)和HQL(Hibernate Query Language)语句查询。这两种查询方法各有特点,适用于不同的场景,使得开发者可以根据实际需求灵活选择。 1. Hibernate ...

    hibernate实现动态SQL查询

    在Hibernate中,我们通常使用HQL(Hibernate Query Language)或Criteria API进行查询,但这些方式并不支持复杂的动态查询。为了实现动态SQL,我们可以借助于Hibernate的QBC(Query By Criteria)和Criteria API,...

    hibernate查询代码

    最后,`hibernate查询`这个压缩包可能包含了一些示例代码和配置文件,用于演示如何在Java项目中实现上述查询方式。通过分析这些文件,你可以更好地理解Hibernate查询的工作原理,并将其应用到自己的项目中。 总之,...

Global site tag (gtag.js) - Google Analytics