spring结合hibernate访问数据库方式的比较

1.直接使用HibernateAPI

public class DaoImp implate Dao{ 
        private SessionFactory sessionFactory; 
        private static String hql = "from User u where u.username=? ";  
        public void setSessionFactory(SessionFactory sessionFactory){                      
		this.sessionFactory=sessionFactory;           
	}  
        public boolean isValidUser(String username) {                  
		try{ 
                     List userList = 
			sessionFactory.getCurrentSession().creatQuery(hql).setParameter(0,username).list();                        
		     if (userList.size() > 0) {                       
			return true;  
                     } catch (HibernateException ex){ 
                      	throw converHibernaterAccessException(ex);                    
		     }                  
		   }  
	} 
}

优点:与Spring框架完全分离 
缺点:(1)无法使用Spring框架封装所提供的额外功能.如,直接使用Hibernate API 需用try...catch()处理HibernateException异常. 
         (2)需在实现类中加入setSessionFactory(SessionFactory sessionFactory)属性,接收依赖注入的SessionFactory. 


2.继承 Spring 的 HibernateDaoSupport 使用 HibernateTemplate (不推荐使用getSession())

public class DaoImp extend HibernateDaoSupport implates Dao{         
         private static String hql = "from User u where u.username=? ";            
	public boolean isValidUser(String username) {  
                     List userList = getHibernateTemplate().find(hql,username); 
                       if (userList.size() > 0) {
                      		 return true;                               
			}  
        public boolean isValidUser(String username,String password) throw DataAccessException {  
                     Session session = getSession();                  //不推荐使用,用完后需手动关闭                      
		     String[] userlist=new String[2];                       
		     userlist[0]=username;                      
                     userlist[1]=password;                   
                     try{ 
                    		List userList = session.find(hql,userlist);       //Hibernate语句;                       
				session.close();                       
				if (userList.size() > 0) {                      
				 	return true;  
                 		} catch (HibernateException ex){ 
                      			throw converHibernaterAccessException(ex);                    
				}                 
			 }  
	}
}
特点:对HibernateTemplate没有提供的功能,可以直接调用HibernateDaoSuppor对象的getSession()方法(极其不推荐使用)得到Session对象实例用try{ Hibernate API }catch (HibernateException ex )操作

3.对 HibernateTemplate 没有提供的功能, 还可以用HibernateCallback 回调的方法管理数据库. (极其推荐)

/** 
* 使用 hql 语句进行操作 
* @param hql       HSQL 查询语句 * @param offset   开始取数据的下标 * @param length    读取数据记录数 * @return List        结果集 */ 
public List getListForPage ( final String hql , final int offset , final int length ) {      
	List list = getHibernateTemplate().executeFind ( new HibernateCallback ( ) { 
        	public Object doInHibernate ( Session session ) throws HibernateException, SQLException { 
                     Query query = session.createQuery ( hql )                       
			query.setFirstResult ( offset )                       
			query.setMaxResults ( length )  
			query.setCacheable(false);    
			 for (int i = 0; i < values.length; i++) {                    
					query.setParameter(i, values[i]);                
			  }    
                    	 List list = query.list ( )                      
			 return list             
		}    
	 })     
	 return list  
} 

4.注入jdbcTemplate

先配置好jdbcTemplate

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">     
	<property name="dataSource">  
    		<ref bean="dataSource" />     
	</property> 
<bean id="classDao" class="cn.jmu.data.dao.impl.ClassImpl">     
	<property name="jdbctemplate">      
		<ref bean="jdbcTemplate" />     
	</property>  
</bean>

</bean><bean id="classDao" class="cn.jmu.data.dao.impl.ClassImpl"> <property name="jdbctemplate"> <ref bean="jdbcTemplate" /> </property> </bean>



jdbcTemplate使用

String SQL= "select name from table";      
List   list= jdbctemplate.queryForList(SQL); 
Hashtable hash = new Hashtable();  
jdbctemplate.query(SQL, new RowCallbackHandler() {  
       	public void processRow(ResultSet rs) throws SQLException {              
		hash.put(rs.getString(1),rs.getString(2));       
	 }   
 });








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值