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));       
	 }   
 });








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章