Hibernate中的createQuery查询一条数据、多条数据、分页查询数据

package com.ckinghan.test;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;
import org.junit.Test;

import com.ckinghan.bean.User;

public class HibernateQueryApi {

    /**
     * Hibernate 中的createQuery查询一条数据、多条数据、分页查询数据
     */
    @Test
    public void hibernateQuery1(){
        //加载Hibernate的配置文件信息
        Configuration configuration = new Configuration().configure();
        //通过配置文件信息创建SessionFactory
        SessionFactory buildSessionFactory = configuration.buildSessionFactory();
        //通过SessionFactory获取与当前线程绑定的Session
        Session currentSession = buildSessionFactory.getCurrentSession();
        //对Session启动事务 
        Transaction transaction = currentSession.beginTransaction();
        //创建HQL的查询语句
        Query createQuery = currentSession.createQuery("from User where id = 1");

        //获取一条数据,但要注意,如果查询返回的结果集是多条数据,会报错,如果未查询到数据,返回null
        User user  = (User) createQuery.uniqueResult();
        System.out.println("查询一条数据:");
        System.out.println(user);

        //获取多条数据,不管是调用uniqueResult()方法时还是调用list方法,都会重新执行一次SQL查询语句
        List users = (List) createQuery.list();
        System.out.println("查询多条数据:");
        System.out.println(users);

        //分页功能,设置分页的起始索引
        createQuery.setFirstResult(0);
        //设置分页每次获取的数据数量
        createQuery.setMaxResults(100);
        //查询数据
        createQuery = currentSession.createQuery("from User");
        List list = createQuery.list();
        //输出查询到的结果集
        System.out.println("分页查询数据:");
        System.out.println(list);

        //提交事务
        transaction.commit();
        //关闭SessionFactory
        buildSessionFactory.close();
    }
}

执行结果 如下:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Hibernate: 
    select
        user0_.id as id0_,
        user0_.userName as userName0_,
        user0_.password as password0_ 
    from
        user user0_ 
    where
        user0_.id=1
查询一条数据:
User [id=1, userName=userName, password=password123]
Hibernate: 
    select
        user0_.id as id0_,
        user0_.userName as userName0_,
        user0_.password as password0_ 
    from
        user user0_ 
    where
        user0_.id=1
查询多条数据:
[User [id=1, userName=userName, password=password123]]
Hibernate: 
    select
        user0_.id as id0_,
        user0_.userName as userName0_,
        user0_.password as password0_ 
    from
        user user0_
分页查询数据:
[User [id=1, userName=userName, password=password123], User [id=2, userName=userName, password=password123]]

你可能感兴趣的:(Hibernate)