hibernate简括

1:Hibernate的多条件查询通用方法(查询条件个数不限,能进行模糊、精确2种查询)

//value[i]为第i个查询条件propertyName[i]的值          (本方法已通过测试)

/*多条件查询,查询条件的值为空时自动除去该条件
* rigor为true时采用精确查询
*/
public List searchByPropertys(String model,String[]propertyName,Object[] value,int page,boolean rigor){  
    StringBuffer sqlBuffer = new StringBuffer();
    String ralation=" like ";
    if(rigor){
     ralation=" = ";
    }
    sqlBuffer.append("from "+model+" as model\n");
    int len=propertyName.length;
    List list=new ArrayList();
    boolean first=true;
    for(int i=0;i<len;i++){
     if(value[i]!=null){
     if(first){    
      sqlBuffer.append(" where "+ "model."+ propertyName[i] + ralation+" ?\n");    
      list.add(value[i]);
      first=false;
     }else{    
      sqlBuffer.append(" and "+ "model."+ propertyName[i] +ralation+ " ?\n");    
      list.add(value[i]);
     }
    }
    }
  
     try {          
      Session session=getSession();
             Query queryObject = session.createQuery(sqlBuffer.toString());
             for(int i=0;i<list.size();i++){
             if(rigor){
              queryObject.setParameter(i, list.get(i));
             }else{
              queryObject.setParameter(i, "%"+list.get(i)+"%");
             }
           
      }
          
            list=queryObject.list();
            closeSession(session);
      return list;
         } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
         }

}

转自:

http://hi.baidu.com/xiehaisheng/blog/item/4ebe3001a9b71f0c7bec2c86.html

 

2:hibernate 多条件组合查询 之 sql 拼接

这个方法与上面第一节中的相同,只不过上面的方法是将搜索的多个条件在外部(即调用方)封装在了数组中。

  1. public static void main(String[] args) {   
  2.           
  3.        Session session = null;   
  4.        Transaction tx = null;   
  5.        List list = null;   
  6.        Criteria criteria = null;   
  7.     
  8.        try {   
  9.     
  10.            session = HibernateSessionFactory.getSession();   
  11.            tx = session.beginTransaction();   
  12.     
  13.            DetachedCriteria detachedCriteria = DetachedCriteria   
  14.                   .forClass(InfoTab.class);   
  15.               
  16.               
  17.            String sql=" 1=1 ";   
  18.               
  19.            Integer pareaId = 0// 父地区;   
  20.            Integer careaId = 0// 子地区;   
  21.            Integer categoryId = 0// 类别;   
  22.            String infoPrivider = "中介"// 来源;   
  23.            String houseType= "地下室"// 房屋类型;   
  24.            Integer hxBedRoom=0// 室;   
  25.            Integer hxLivingRoom=0// 厅;   
  26.               
  27.            String hzHouseStatus="有房出租"// 合租类型;   
  28.            String hzRequestSex="男"// 性别要求;   
  29.            String fixUp="尚未"// 装修程度;   
  30.            Integer lcHeightMolecuse=0// 楼层;   
  31.            String orientation="东南"// 朝向要求;   
  32.            Integer buildArea=2000// 建筑面积;   
  33.            Integer useArea=80// 使用面积;   
  34.            Integer rentalDigit=2000// 租金/价格;   
  35.            String title= "出租"// 标题;   
  36.               
  37.            if(pareaId!=0)   
  38.            {   
  39.               sql+="pareaId=" + pareaId;   
  40.            }   
  41.            if(careaId!=0)   
  42.            {   
  43.               sql+=" and careaId=" + careaId;   
  44.            }   
  45.            if(categoryId!=0)   
  46.            {   
  47.               sql+=" and categoryId=" + categoryId;   
  48.            }   
  49.            if(!infoPrivider.equals(""))   
  50.            {   
  51.               sql+=" and infoPrivider='" + infoPrivider + "'";   
  52.            }   
  53.            if(!houseType.equals(""))   
  54.            {   
  55.               sql+=" and houseType='" + houseType +"'";   
  56.            }   
  57.            if(hxBedRoom!=0)   
  58.            {   
  59.               sql+=" and hxBedRoom=" + hxBedRoom;   
  60.            }   
  61.            if(hxLivingRoom!=0)   
  62.            {   
  63.               sql+=" and hxLivingRoom=" + hxLivingRoom;   
  64.            }   
  65.            if(!hzHouseStatus.equals(""))   
  66.            {   
  67.               sql+=" and hzHouseStatus='" + hzHouseStatus + "'";   
  68.            }   
  69.            if(!hzRequestSex.equals(""))   
  70.            {   
  71.               sql+=" and hzRequestSex='" + hzRequestSex +"'";   
  72.            }   
  73.            if(!fixUp.equals(""))   
  74.            {   
  75.               sql+=" and fixUp='" + fixUp + "'";   
  76.            }   
  77.            if(lcHeightMolecuse!=0)   
  78.            {   
  79.               sql+=" and lcHeightMolecuse=" + lcHeightMolecuse;   
  80.            }   
  81.            if(!orientation.equals(""))   
  82.            {   
  83.               sql+=" and orientation='" + orientation + "'";   
  84.            }   
  85.            if(buildArea!=0)   
  86.            {   
  87.                sql+=" and buildArea=" + buildArea;   
  88.            }   
  89.            if(useArea!=0)   
  90.            {   
  91.               sql+=" and useArea=" + useArea;   
  92.            }   
  93.            if(rentalDigit!=0)   
  94.            {   
  95.               sql+=" and rentalDigit=" + rentalDigit;   
  96.            }   
  97.            if(!title.equals(""))   
  98.            {   
  99.               sql+=" and title like '%" + title + "%'";   
  100.            }   
  101.            sql+=" order by id desc";   
  102.               
  103.            System.out.println(sql);   
  104.     
  105.            detachedCriteria.add(Restrictions.sqlRestriction(sql));   
  106.     
  107.            criteria = detachedCriteria.getExecutableCriteria(session);   
  108.     
  109.            list = criteria.list();   
  110.               
  111.            for(int i=0;i<list.size();i++)   
  112.            {   
  113.               InfoTab infoTab = (InfoTab)list.get(i);   
  114.               System.out.println(infoTab.getTitle() +" "+ infoTab.getCategoryId() +" "+ infoTab.getPareaName() +" "+ infoTab.getCareaName() +" " + infoTab.getHouseType() +" " + infoTab.getInfoPrivider());   
  115.            }   
  116.     
  117.            tx.commit();   
  118.     
  119.        } catch (HibernateException he) {   
  120.            he.printStackTrace();   
  121.        }   
  122.     }   
  123. 本文出自 “maomao” 博客,请务必保留此出处http://maomao.blog.51cto.com/115985/33883   
  124.  


3:HQL查询简括

  • 摘要:本文介绍了Hibernate HQL查询,分为简单属性查询、实体对象查询、条件查询、直接使用spl进行查询等八种进行介绍。

在HQL中关键字不区分大小写,但是属性和类名区分大小写,下面介绍各种类型的Hibernate的HQL查询。
1、Hibernate HQL查询:简单属性查询

* 单一属性查询,返回结果集属性列表,元素类型和实体类中相应的属性类型一致

* 多个属性查询,返回的集合元素是对象数组,数组元素的类型和对应的属性在实体类中的类型一致
数组的长度取决与select中属性的个数

* 如果认为返回数组不够对象化,可以采用HQL动态实例化Student对象

2、Hibernate HQL查询:实体对象查询

* N + 1问题,在默认情况下,使用query.iterate查询,有可以能出现N+1问题,所谓的N+1是在查询的时候发出了N+1条sql语句,1: 首先发出一条查询对象id列表的sql,N: 根据id列表到缓存中查询,如果缓存中不存在与之匹配的数据,那么会根据id发出相应的sql语句

* list和iterate的区别?

* list每次都会发出sql语句,list会向缓存中放入数据,而不利用缓存中的数据

* iterate:在默认情况下iterate利用缓存数据,但如果缓存中不存在数据有可以能出现N+1问题

3、Hibernate HQL查询:条件查询

* 可以采用拼字符串的方式传递参数

Java代码:

  1. List students = session.createQuery
  2. ("select s.id, s.name from Student s where s.name like '%1%'").list();    

* 可以采用 ?来传递参数(索引从0开始)

Java代码:

  1. List students = session.createQuery
  2. ("select s.id, s.name from Student s where s.name like ?").setParameter(0"%1%").list();      
  3. //可以使用?方式传递参数      
  4. //参数的索引从0开始      
  5. //传递的参数值,不用单引号引起来      
  6. //注意方法链编程    

* 可以采用 :参数名 来传递参数

Java代码:

  1. List students = session.createQuery  
  2. ("select s.id, s.name from Student s where s.name like :myname").
  3. setParameter("myname""%1%").list();    

* 如果传递多个参数,可以采用setParamterList方法

Java代码:

  1. List students = session.createQuery
  2. ("select s.id, s.name from Student s where s.id in(:myids)").
  3. setParameterList("myids"new Object[]{12345}).list();    

* 在HQL中可以使用数据库的函数,如:date_format

Java代码:

  1. List students = session.createQuery
  2. ("select s.id, s.name from Student s where date_format(s.createTime, '%Y-%m')=?").
  3. setParameter(0"2008-02").list();      
  4. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      
  5.          
  6.    //查询2008-01-10到2008-02-15创建的学生      
  7.     List students = session.createQuery
  8. ("select s.id, s.name from Student s where s.createTime between ? and ?")      
  9.           .setParameter(0, sdf.parse("2008-01-10 00:00:00"))      
  10.           .setParameter(1, sdf.parse("2008-02-15 23:59:59"))      
  11.                 .list();     

4、Hibernate HQL查询:直接使用sql进行查询

Java代码:

  1. List students = session.createSQLQuery("select * from t_student").list();    


不会返回对象,而是所有属性!  


5、Hibernate HQL查询:分页查询

* setFirstResult(),从0开始

* setMaxResults,每页显示多少条数据

Java代码:

  1. List students = session.createQuery("from Student")      
  2.           .setFirstResult(1)      
  3.           .setMaxResults(2)      
  4.           .list();    

6、Hibernate HQL查询:对象导航查询,在HQL中采用 . 进行导航

7、Hibernate HQL查询:连接查询

* 内连

Sql代码:

  1. SELECT s.name, c.name FROM Student s (inner) join s.classes c    

* 外连接(左连接/右连接)

Sql代码:

  1. SELECT s.name, c.name FROM Student s left join s.classes c    

8、Hibernate HQL查询:统计查询

Java代码:

  1. List students =session.createQuery
  2. ("select c.name, count(s) from Student s join s.classes c " 
  3. +"group by c.name order by c.name").list();      
  4. for (Iterator iter=students.iterator(); iter.hasNext();) {      
  5.      Object[] obj = (Object[])iter.next();      
  6.      System.out.println(obj[0] + ", " + obj[1]);      
  7. }    

9、DML风格的操作(尽量少用,因为和缓存不同步)

Java代码:

  1. session.createQuery  
  2. ("update Student s set s.name=? where s.id < ?")      
  3.                      .setParameter(0"李四")      
  4.                      .setParameter(15)      
  5.                      .executeUpdate();    

应当尽量少用,因为和缓存不同步,也就是说,假如在执行上面的语句之前,已经把student封装成一个list曾经拿了出来,再执行上面的语句对 student中的表进行数据更新,然后再list Student表,则此时的list是从缓存中取的数据,而不是从表中找到的数据,也就是说,list拿到的是update前的数据,所以造成了这种不同步,所以这种风格尽量少用。

从这个方面也可以看得出Hibernate并不适用于聚集性,统计,大量批量的更新,删除等操作。

 

4:接下来给个强人笔记:http://developer.51cto.com/art/200906/129500.htm

 

 

posted @ 2009-06-25 15:52  弹着钢琴设计  阅读(287)  评论(0编辑  收藏  举报