首页投稿首页投稿(暂停使用,暂停投稿)Grails实战经验

Hibernate-Criteria接口

2016-06-16  本文已影响533人  慕凌峰

Hibernate Criteria简介

一、Criteria接口的用途:

</br>

二、Criteria查询接口的用法:

</br>


无条件查询,即不输入任何查询条件,此时,会将表中的所有的数据都查询出来
org.hibernate.Criteria接口表示一个特定持久类的查询,Session是Criteria接口的实例工厂。


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;  
<?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="connection.url">
        jdbc:oracle:thin:@127.0.0.1:1521:XE
    </property>
    <!-- 连接数据库的驱动 -->
    <property name="connection.driver_class">
        oracle.jdbc.driver.OracleDriver
    </property>
    <!-- 连接数据库的用户名和密码 -->
    <property name="connection.username">SYSTEM</property>
    <property name="connection.password">SYSTEM</property>
    <!-- 连接数据库用的方言 -->
    <property name="dialect">
        org.hibernate.dialect.Oracle10gDialect
    </property>
    
    <!--第二部分: Hibernate框架的基本属性 -->
    
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <!--自动建表   或者 create 删除再创建,只删除做了映射的-->
    <mapping resource="criteria/unconditional/bean/Login.hbm.xml" />

</session-factory>

</hibernate-configuration>  
package criteria.unconditional.bean;

import java.io.Serializable;

public class Login implements Serializable{

    private static final long serialVersionUID = 1L;
    
    private String username;
    private String password;
    private int age;
    
    public Login(){
        
    }
    
    public Login(String username, String password) {
        this.username = username;
        this.password = password;
    }
    
    public Login(String username, String password, int age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }
    
    public int getAge() {
        return age;
    }

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

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    
}

<?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="criteria.unconditional.bean.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 criteria.unconditional.dao;

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 criteria.unconditional.bean.Login;

/**
 * 无条件查询测试类
 * 
 * @author wxf
 *
 */
public class Demo {
    /**
     * 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());
        }
    }
}

  select
    this_.USERNAME as USERNAME0_0_,
    this_.PASSWORD as PASSWORD0_0_,
    this_.AGE as AGE0_0_ 
  from
    ROOT.LOGIN this_

</br>


加入一个username作为查询条件
Restrictions提供了大量的静态方法,eg:eq(等于)、ge(大于等于)、between等方法来创建Criterion 查询条件(SimpleExpression实例)


package criteria.unconditional.dao;

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 criteria.unconditional.bean.Login;

/**
 * 单条件查询 添加username作为查询条件
 * 
 * @author wxf
 *
 */
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);

            // 添加查询条件 Restrictions.eq是等于的意思,2个参数,第一个为持久化类的属性,第2个为比较的参数值
            criteria.add(Restrictions.eq("username", "Tom"));

            // 查询使用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());
        }
    }
}

添加查询条件 Restrictions.eq是等于的意思,2个参数,第一个为持久化类的属性,第2个为比较的参数值
criteria.add(Restrictions.
eq(
"username",
"Tom"));

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

</br>


查询 23 ~ 25 年龄段内的用户信息
Restrictions提供了大量的静态方法,eg:eq(等于)、ge(大于等于)、between等方法来创建Criterion 查询条件(SimpleExpression实例)


//年龄小于等25岁的用户
criteria.add(Restrictions.le("age", 25));
//年龄大于等于23的用户
criteria.add(Restrictions.ge("age", 23));  
//或者直接用between查询  age >= 23 && age <= 25 的用户信息
criteria.add(Restrictions.between("age", 23, 25));  
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 ?

</br>


查询 age = 23 && username 中含有‘李’字的用户
Restrictions提供了大量的静态方法,eg:eq(等于)、ge(大于等于)、between等方法来创建Criterion 查询条件(SimpleExpression实例)


//查询年龄为23岁,或者名字里面有 李 字的用户
criteria.add(Restrictions.or(Restrictions.eq("age", 23),Restrictions.like("username", "%李%")));

//或者直接调用sql语句查询
criteria.add(Restrictions.sqlRestriction("age=23 or username like '%李%'"));  
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 ? )

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 '%李%'

上一篇下一篇

猜你喜欢

热点阅读