Hibernate中的QBC查询

QBC查询

QBC:Query By Criteria条件查询.面向对象的查询的方式.


QBC简单查询

// 简单查询:
		List list = session.createCriteria(Customer.class).list();
		for (Customer customer : list) {
			System.out.println(customer);
		}



QBC分页查询

Criteria criteria = session.createCriteria(Order.class);
		criteria.setFirstResult(10);
		criteria.setMaxResults(10);
		List list = criteria.list();


QBC排序查询

Criteria criteria = session.createCriteria(Customer.class);
//		criteria.addOrder(org.hibernate.criterion.Order.asc("age"));
		criteria.addOrder(org.hibernate.criterion.Order.desc("age"));
		List list = criteria.list();



QBC条件查询

// 按名称查询:
		/*Criteria criteria = session.createCriteria(Customer.class);
		criteria.add(Restrictions.eq("cname", "tom"));
		List list = criteria.list();*/
		
		// 模糊查询;
		/*Criteria criteria = session.createCriteria(Customer.class);
		criteria.add(Restrictions.like("cname", "t%"));
		List list = criteria.list();*/
		
		// 条件并列查询
		Criteria criteria = session.createCriteria(Customer.class);
		criteria.add(Restrictions.like("cname", "t%"));
		criteria.add(Restrictions.ge("age", 35));
		List list = criteria.list();



QBC离线查询

l  DetachedCriteria 离线查询对象,不需要使用Session就可以拼凑查询条件。

一般使用在web层或service层拼凑。将此对象传递给dao层,此时将与session进行绑定执行查询。

l  离线查询条件与QBC一样的。

Hibernate中的QBC查询_第1张图片

@Test
	public void demo10(){
		/* 10 离线查询
		 */
		
		//web & service
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Customer.class);
		detachedCriteria.add(Restrictions.eq("cid", 1));
		
		//---------------dao
		
		Session session = factory.openSession();
		session.beginTransaction();
		
		// 离线Criteria 与session绑定
		Criteria criteria = detachedCriteria.getExecutableCriteria(session);
		List allCustomer = criteria.list();
		System.out.println(allCustomer.size());
		
		session.getTransaction().commit();
		session.close();
	}



case:
package com.itheima.d_qbc;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.junit.Test;

import com.itheima.domain.Customer;
import com.itheima.utils.HibernateUtils;
//QBC 离线查询
public class Demo {
	@Test
	public void fun1(){
		//Service层
			DetachedCriteria dc = DetachedCriteria.forClass(Customer.class);
			dc.add(Restrictions.eq("id", 1));
		//-------------------------------------------------
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		//------------------------------------------------
		Criteria c = dc.getExecutableCriteria(session);
		
		System.out.println(c.list());
		//------------------------------------------------
		session.getTransaction().commit();
		session.close(); // 游离状态
	}
}



你可能感兴趣的:(JavaEE,hibernate)