Hibernate离线查询

  简述离线查询可以通过Map从前端接收用户的查询条件,在业务层使用离线的Criteria进行动态SQL的拼接完成查询

Service层

注意:sal是实体类的对应的属性!!!

 1 //离线查询对象
 2     public List<Emp> empList(Map<String,Object> map){
 3         List<Emp> emps=null;
 4         tx=HibernateSessionFactory.getSession().beginTransaction();
 5         DetachedCriteria criteria=DetachedCriteria.forClass(Emp.class);//创建离线对象
 6         if(map.get("salary")!=null&&!"".equals(map.get("salary"))){
 7             criteria.add(Restrictions.ge("sal", map.get("salary")));
 8         }
 9         /*if(map.get("begin")!=null&&!"".equals(map.get("salary"))){
10             //条件
11         }*/
12         emps=empDao2.empList(criteria);
13         tx.commit();
14         return emps;
15     }

Dao层:将离线的Detachedcriteria与session建立联系

1 public List<Emp> empList(DetachedCriteria criteria){
2         return criteria.getExecutableCriteria(HibernateSessionFactory.getSession()).list();       
3    }

测试方法:

1 public static void main(String [] args){
2         EmpService2 empService2=new EmpService2();
3         Map<String, Object> map=new HashMap<String, Object>();
4         map.put("salary",200.00);
5         List<Emp> empList=empService2.empList(map);
6         for (Emp emp : empList) {
7             System.out.println(emp.geteName()+"======"+emp.getSal());
8         }
9     }

 

posted @ 2018-03-20 23:19  Quest1on  阅读(175)  评论(0编辑  收藏  举报