Hibernate(十一)Criteria查詢


一、簡述

Criteria是一種比hql更面向對象的查詢方式。Criteria 可使用 Criterion 和 Projection 設置查詢條件。可以設置 FetchMode(聯合查詢抓取的模式 ) ,設置排序方式,Criteria 還可以設置 FlushModel (沖刷 Session 的方式)和 LockMode (數據庫鎖模式)。

Criteria本身只是查詢的容器。Criteria查詢又稱對象查詢

Criteria查詢采用面向對象的方式封裝查詢條件。由Hibernater自動生成SQL查詢語句

二、不帶查詢條件

 建立數據表

復制代碼
create table login
(
username
varchar2(32) primary key,
password
varchar2(32) not null ,
age
number(3)
);

insert into login
select '張三','123456',21 from dual union
select 'Tom','123123',34 from dual union
select 'Jack','12345678',34 from dual union
select '李四','qwerty',23 from dual;
commit;
復制代碼

建立持久化類和配置文件

Hibernate.cfg.xml配置文件

復制代碼
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
>
<hibernate-configuration>

<session-factory>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:orcl
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>

<mapping resource="entity/Login.hbm.xml" />

</session-factory>

</hibernate-configuration>
復制代碼

持久化類和配置文件 

復制代碼
package entity;


public class Login implements java.io.Serializable {

// Fields

/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private int age;

// Constructors

/** default constructor */
public Login() {
}

/** minimal constructor */
public Login(String username, String password) {
this.username = username;
this.password = password;
}

/** full constructor */
public Login(String username, String password, int age) {
this.username = username;
this.password = password;
this.age = age;
}

// Property accessors

public String getUsername() {
return this.username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return this.password;
}

public void setPassword(String password) {
this.password = password;
}

public int getAge() {
return this.age;
}

public void setAge(int age) {
this.age = age;
}

}
復制代碼

配置文件Login.hbm.xml

復制代碼
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"
>

<hibernate-mapping>
<class name="entity.Login" table="LOGIN" schema="ROOT">
<id name="username" type="java.lang.String">
<column name="USERNAME" length="32" />
<generator class="assigned" />
</id>
<property name="password" type="java.lang.String">
<column name="PASSWORD" length="32" not-null="true" />
</property>
<property name="age" type="java.lang.Integer">
<column name="AGE" precision="3" scale="0" />
</property>
</class>
</hibernate-mapping>
復制代碼

測試類:

復制代碼
package demo;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import entity.Login;

public class Demo1 {

/**
* Criteria無查詢條件查詢所有
*/
public static void main(String[] args) {
//聲明一個集合用來接收結果
List<Login> result=null;
//聲明SessionFactory
SessionFactory factory=null;
//聲明Session
Session session=null;
//初始化以上對象
try{
factory
=new Configuration().configure().buildSessionFactory();
session
=factory.openSession();
//聲明Criteria對象傳入一個持久化類對象類型
Criteria criteria=session.createCriteria(Login.class);
//查詢使用list方法
result=criteria.list();
}
catch(HibernateException e){
e.printStackTrace();
}
finally{
session.close();
factory.close();
}
//輸出結果
for (Login login : result) {
System.out.println(
"用戶名:"+login.getUsername()+" 密碼:"+login.getPassword()+" 年齡:"+login.getAge());
}



}


}
復制代碼

結果:

復制代碼
Hibernate: 
select
this_.USERNAME as USERNAME0_0_,
this_.PASSWORD as PASSWORD0_0_,
this_.AGE as AGE0_0_
from
ROOT.LOGIN this_
用戶名:Jack 密碼:
12345678 年齡:34
用戶名:Tom 密碼:
123123 年齡:34
用戶名:李四 密碼:qwerty 年齡:
23
用戶名:張三 密碼:
123456 年齡:21
復制代碼

三、添加查詢條件

3.1、加入一個username的條件

復制代碼
    //聲明Criteria對象傳入一個持久化類對象類型
Criteria criteria=session.createCriteria(Login.class);
//添加查詢條件 Restrictions.eq是等於的意思,2個參數,第一個為持久化類的屬性,第2個為比較的參數值

criteria.add(Restrictions.eq(
"username", "Tom"));
//查詢使用list方法
result=criteria.list();
復制代碼

執行的SQL

復制代碼
    select
this_.USERNAME
as USERNAME0_0_,
this_.PASSWORD
as PASSWORD0_0_,
this_.AGE
as AGE0_0_
from
ROOT.LOGIN this_
where
this_.USERNAME
=?
復制代碼

3.2、多個查詢條件AND--between

//年齡在大於等於25
criteria.add(Restrictions.le("age", 25));
//年齡小於等於23
criteria.add(Restrictions.ge("age", 23));

或者

//年年齡大於23小於25之間的記錄
criteria.add(Restrictions.between("age", 23, 25));

執行的SQL

復制代碼
 select
this_.USERNAME
as USERNAME0_0_,
this_.PASSWORD
as PASSWORD0_0_,
this_.AGE
as AGE0_0_
from
ROOT.LOGIN this_
where
this_.AGE
<=?
and this_.AGE>=?
復制代碼
復制代碼
select
this_.USERNAME
as USERNAME0_0_,
this_.PASSWORD
as PASSWORD0_0_,
this_.AGE
as AGE0_0_
from
ROOT.LOGIN this_
where
this_.AGE
between ? and ?
復制代碼

3.3、多個查詢條件或者條件 or

criteria.add(Restrictions.or(Restrictions.eq("age", 23), Restrictions.like("username", "%李%")));
//或者以下寫法直接使用SQL語句
criteria.add(Restrictions.sqlRestriction("age=20 or username like '%李%'"));

執行SQL

復制代碼
 select
this_.USERNAME
as USERNAME0_0_,
this_.PASSWORD
as PASSWORD0_0_,
this_.AGE
as AGE0_0_
from
ROOT.LOGIN this_
where
(
this_.AGE
=?
or this_.USERNAME like ?
)
復制代碼

直接使用SQL的執行語句

復制代碼
 select
this_.USERNAME
as USERNAME0_0_,
this_.PASSWORD
as PASSWORD0_0_,
this_.AGE
as AGE0_0_
from
ROOT.LOGIN this_
where
age
=20
or username like '%李%'
復制代碼

四、Restrictions常用方法

五、常用方法使用

復制代碼
package demo;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

import entity.Login;

public class Demo1 {

/**
* Criteria無查詢條件查詢所有
*/
public static void main(String[] args) {
//聲明一個集合用來接收結果
List<Login> result=null;
//聲明SessionFactory
SessionFactory factory=null;
//聲明Session
Session session=null;
//初始化以上對象
try{
factory
=new Configuration().configure().buildSessionFactory();
session
=factory.openSession();
//聲明Criteria對象傳入一個持久化類對象類型
Criteria criteria=session.createCriteria(Login.class);
//1.查詢用戶名為Tom的記錄
//criteria.add(Restrictions.eq("username", "Tom"));
//2.查詢年齡大於等於21同時小於等於25的記錄
//criteria.add(Restrictions.ge("age", 21));
//criteria.add(Restrictions.le("age", 25));
//between寫法
//criteria.add(Restrictions.between("age", 21, 25));
//3.或者查詢年齡=21或者名字中有李的記錄
//criteria.add(Restrictions.or(Restrictions.eq("age", 21), Restrictions.like("username", "%李%")));
//sql寫法
//criteria.add(Restrictions.sqlRestriction("age=21 or username like '%李%'"));
//4.年齡在21,23,25的記錄
//criteria.add(Restrictions.in("age", new Integer []{21,23,25}));
//5.and用法
criteria.add(Restrictions.and(Restrictions.ge("age", 23), Restrictions.like("username", "%T%")));

//查詢使用list方法
result=criteria.list();
}
catch(HibernateException e){
e.printStackTrace();
}
finally{
session.close();
factory.close();
}
System.out.println(
"==========");
//輸出結果
for (Login login : result) {
System.out.println(
"用戶名:"+login.getUsername()+" 密碼:"+login.getPassword()+" 年齡:"+login.getAge());
}



}


}
復制代碼

 六、對結果進行排序

使用Order關鍵字,進行排序

criteria.addOrder(Order.desc(屬性名稱));降序

criteria.addOrder(Order.asc(屬性名稱));升序

復制代碼
//按年齡降序排序
criteria.addOrder(Order.desc("age"));
//按姓名升序排序
criteria.addOrder(Order.asc("username"));
//查詢使用list方法
result=criteria.list();
//輸出結果
for (Login login : result) {
System.out.println(
"用戶名:"+login.getUsername()+" 密碼:"+login.getPassword()+" 年齡:"+login.getAge());
}
復制代碼

七、示例查詢

復制代碼
package demo;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import entity.Login;

public class Demo2 {

/**
* Criteria無查詢條件查詢所有
*/
public static void main(String[] args) {
//聲明一個集合用來接收結果
List<Login> result=null;
//聲明SessionFactory
SessionFactory factory=null;
//聲明Session
Session session=null;
//聲明一個Login對象,並賦值可以是多個 但不能是主鍵
Login user=new Login();
user.setAge(
21);

//初始化以上對象
try{
factory
=new Configuration().configure().buildSessionFactory();
session
=factory.openSession();
//聲明Criteria對象傳入一個持久化類對象類型
Criteria criteria=session.createCriteria(Login.class);
//加入查詢條件
criteria.add(Example.create(user));

//查詢使用list方法
result=criteria.list();
}
catch(HibernateException e){
e.printStackTrace();
}
finally{
session.close();
factory.close();
}
System.out.println(
"==========");
//輸出結果
for (Login login : result) {
System.out.println(
"用戶名:"+login.getUsername()+" 密碼:"+login.getPassword()+" 年齡:"+login.getAge());
}



}


}
復制代碼

八、聚合函數

 

復制代碼
package demo;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;

import entity.Login;

public class Demo3 {

/**
* Criteria無查詢條件查詢所有
*/
public static void main(String[] args) {
//聲明一個集合用來接收結果
List<Login> result=null;
//聲明SessionFactory
SessionFactory factory=null;
//聲明Session
Session session=null;

//初始化以上對象
try{
factory
=new Configuration().configure().buildSessionFactory();
session
=factory.openSession();
//聲明Criteria對象傳入一個持久化類對象類型
Criteria criteria=session.createCriteria(Login.class);
//加入查詢條件
//總記錄數
//criteria.setProjection(Projections.rowCount());
//平均年齡
//criteria.setProjection(Projections.avg("age"));
//分組
criteria.setProjection(Projections.groupProperty("username"));
//查詢使用list方法
result=criteria.list();
//System.out.println("平均年齡:"+result.iterator().next());
//System.out.println("總記錄數:"+result.iterator().next());
Iterator iterator=result.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
catch(HibernateException e){
e.printStackTrace();
}
finally{
session.close();
factory.close();
}



}


}
復制代碼

 分頁

復制代碼
package demo;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import entity.Login;

public class Demo4 {

/**
* Criteria無查詢條件查詢所有
*/
public static void main(String[] args) {
//聲明一個集合用來接收結果
List<Login> result=null;
//聲明SessionFactory
SessionFactory factory=null;
//聲明Session
Session session=null;
//當前頁數第幾頁
int pageIndex=1;
//最大顯示記錄數
int pageSize=2;
//初始化以上對象
try{
factory
=new Configuration().configure().buildSessionFactory();
session
=factory.openSession();
//聲明Criteria對象傳入一個持久化類對象類型
Criteria criteria=session.createCriteria(Login.class);
//起始記錄數
criteria.setFirstResult((pageIndex-1)*pageSize);
//每頁顯示最大記錄數
criteria.setMaxResults(pageSize);


//查詢使用list方法
result=criteria.list();
}
catch(HibernateException e){
e.printStackTrace();
}
finally{
session.close();
factory.close();
}
System.out.println(
"==========");
//輸出結果
for (Login login : result) {
System.out.println(
"用戶名:"+login.getUsername()+" 密碼:"+login.getPassword()+" 年齡:"+login.getAge());
}

}

}
復制代碼

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com