Hibernate 自定义sql 01

我们一般在用到Hibernate写sql查询时,有的时候list 中的Object并不是已有的Model,所以一般我们会重新新建一个Model。

     方法一:在Dao层中编写。Spring框架支持持久层开发

public List<MyObj> getList(int rid, String name){      
         List<MyObj> list = new ArrayList();     
         Connection conn = null;      
         Statement cs = null;      
         ResultSet rs = null;      
         try{           
              conn = 
       SessionFactoryUtils.getDataSource(getSessionFactory()).getConnection();           
                 String sql = "...";           
                 cs = conn.createStatement();           
                 rs = cs.executeQuery(sql);          
                 int orderIndex = 1;           
                 while(rs.next){              
                 MyObj obj = new MyObj(orderIndex);              
                 obj.setCode(rs.getFloat("code"));              
                 obj.setName(rs.getName("name"));     
                 ....
                 orderIndex++;
                 list.add(obj);    
              }                 
              if(rs!=null){
                  rs.close();
              }   
              if(cs!=null){
                   cs.close();
              }
          }catch (SQLException e) {
	log.error("call package_statistics.statistics_subject1错误!",e);
          } finally {
	if (rs != null)
	try {
                     rs.close();
	} catch (Exception e) {
	}
	if (cs != null)
	try {
	     cs.close();
	} catch (Exception e) {
	}
	try {
	     if (conn != null) {
	           conn.close();
	     }
	} catch (Exception e) {
	}
       }
}

 方法二、在Dao

 

public List<TMember> infoListByTMember(String sql) {
		List<TMember> list = new ArrayList<TMember>();
		Session session = null;
		Transaction t = null;
		try {
			session = getSessionFactory().openSession();
			t = session.beginTransaction();
			SQLQuery query = session.createSQLQuery(sql);
			// 1、将查询结果转换成List<Map<字段名,字段值>>
			query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			// 2、将结果转换成指定的bean List<你的指定javaBean>
			query.setResultTransformer(Transformers.aliasToBean(TMember.class));
			list = query.list();
			t.commit();
		} catch (Exception e) {
			e.printStackTrace();
			t.rollback();
		} finally {
			t = null;
			session.close();
		}
		return list;
	}

 

    

    

posted on 2012-02-08 14:46  it_code  阅读(2788)  评论(0编辑  收藏  举报