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]]