package com.etc.test;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import com.etc.dao.HibernateSessionFactory;
import com.etc.entity.Person;
import com.etc.entity.Sex;
public class cri查询
{
static void 基础的cri查询()
{
//1 获取session连接
Session s = HibernateSessionFactory.getSession();
//2 获取Criteria对象(查询标准)
Criteria cri = s.createCriteria(Person.class);
//3 配置各种查询约束条件
//添加约束:pid等于1
cri.add(Restrictions.ge("pid", 2))
.add(Restrictions.like("pname", "老%"));
/*
Criteria cri2 = s.createCriteria(Sex.class);
cri2.add(Restrictions.sizeEq("persons", 3));
*/
//cri.add(Restrictions.or(Restrictions.ge("pid", 2), Restrictions.like("pname", "老%")));
//4 查询结果
/*
List<Sex> list = cri2.list();
for(Sex sex:list)
{
System.out.println(sex);
}
*/
List<Person> list = cri.list();
for(Person p:list)
{
System.out.println(p);
}
//5 关闭
HibernateSessionFactory.closeSession();
}
static void cri关联条件查询()
{
//例子:找出性别含有”未知“关键字的所有人
//1 获取session连接
Session s = HibernateSessionFactory.getSession();
//2 获取Criteria对象(查询标准)
Criteria cri1 = s.createCriteria(Person.class);
//3 创建关联对象的查询cri对象
Criteria cri2 = cri1.createCriteria("sex");
cri2.add(Restrictions.like("sexname", "%未知%"));
List<Person> list = cri1.list();
for(Person p:list)
{
System.out.println(p);
}
}
static void 离线查询()
{
//1 在未进行数据库连接时,创建离线查询的对象
DetachedCriteria dri = DetachedCriteria.forClass(Person.class);
dri.add(Restrictions.eq("pid", 2));
//2 一旦发现处于连接状态,则可将离线查询转出在线查询
Session s = HibernateSessionFactory.getSession();
Criteria cri = dri.getExecutableCriteria(s);
//3 执行查询
List<Person> list = cri.list();
for(Person p:list)
{
System.out.println(p);
}
}
public static void main(String[] args)
{
//基础的cri查询();
//cri关联条件查询();
离线查询();
}
}