您的位置:首页 > 产品设计 > UI/UE

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

2017-10-01 12:28 459 查看
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<User> users = (List<User>) createQuery.list();
System.out.println("查询多条数据:");
System.out.println(users);

//分页功能,设置分页的起始索引
createQuery.setFirstResult(0);
//设置分页每次获取的数据数量
createQuery.setMaxResults(100);
//查询数据
createQuery = currentSession.createQuery("from User");
List<User> 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]]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息