hibernate(十)之离线查询

1.离线查询:就是查询的对象DetachedCriteria 是离线的,创建时无需Session。当然与之对应的就是在线查询

2.配置文件,实体bean可以参考一对一实例

3.主要是测试代码

package unit.test;

import java.util.List;

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

import com.sinoi.domain.IdCard;
import com.sinoi.domain.Person;
import com.sinoi.util.HibernateUtil;


public class UnitTest {
 @Test
 public void save() {
  Session session = HibernateUtil.getSession();
  session.beginTransaction();
  
  Person person1 = new Person();
  person1.setName("beanGou1");
  person1.setAge(12);
  Person person2 = new Person();
  person2.setName("beanGou2");
  person2.setAge(12);
  
  IdCard card = new IdCard();
  card.setIdNum("abcde");
  card.setPerson(person1);
  
  session.persist(card);
  session.persist(person1);
  session.persist(person2);
  
  session.getTransaction().commit();
  
 }
 
 //´Ó ´Ó¶ÔÏó²éѯ
 @Test
 public void load() {
  Session session = HibernateUtil.getSession();
  IdCard card = (IdCard) session.load(IdCard.class, 1);
  Hibernate.initialize(card);
  session.close();
  System.out.println("card no " + card.getIdNum());
//  System.out.println("person name " + card.getPerson().getName());
 }
 
 //´Ó ´Ó¶ÔÏó²éѯ
 @Test
 public void query1() {
  Session session = HibernateUtil.getSession();
  IdCard card = (IdCard) session.get(IdCard.class, 1);
  System.out.println("card no " + card.getIdNum());
  System.out.println("person name " + card.getPerson().getName());
 }
 
 //´Ó Ö÷¶ÔÏó²éѯ
 @Test
 public void query2() {
  Session session = HibernateUtil.getSession();
  Person person = (Person) session.get(Person.class, 1);
  System.out.println("person name " + person.getName());
  System.out.println("card no " + person.getIdCard().getIdNum());
 }
 
 //离线查询
 @Test
 public void offLineQuery() {
  DetachedCriteria dc = DetachedCriteria.forClass(Person.class);
  if(name!= null && !"".equals(name)) {

dc.add(Restrictions.eq("name", "beanGou"));

}

if(...) {

......

}
  List<Person> list = dc(dc);
  System.out.println(list.size());
  System.out.println(list.get(0).getName());
 }
 
 static List dc(DetachedCriteria criteria) {
  Session session = HibernateUtil.getSession();
  Criteria c = criteria.getExecutableCriteria(session);
  List rs = c.list();
  session.close();
  return rs;
 }
 
}

在红黄色部分,可以通过增加不同的条件,就可以实现多条件查询了

 

你可能感兴趣的:(组合条件查询,离线查询)