hibernate和spring的整合

来源:互联网 发布:java触屏通用版 编辑:程序博客网 时间:2024/04/29 21:37
 
一,整合带来的好处
整合spring和hibernate后较纯hibernate会给我们带来哪些方便呢?
我认为主要有下面几点:
1         利用IOC进行业务对象与持久化对象的生成及组合,如果整合了struts,则还可以一并组织管理Action。这样我们就无需手工创建及组织。
2         利用aop功能为数据库操作增加事务管理,这是我们的持久层代码大大简化,在将不会出现任何关于事务的代码。事务统一由spring进行管理。
3         无须对session进行管理,不用编写session的获得与关闭代码。
这样,我们的持久层代码就会大大的简化。去掉了大部分冗余繁琐的代码。
二,如何整合?
Spring提供了多种整合方法,我认为最有效的一种是继承HibernateDaoSupport来实现DAO。
继承了HibernateDaoSupport的类可以通过this.getHibernateTemplate()获得到一个HibernateTemplate对象。这个对象可以理解成对Session的封装(只是理解成而已),使用它你可以做一些使用session做的事情,如查询单个对象,删除,简单查询。但是比较复杂操作的就有可能无法完成(如复杂查询),对于这种情况我们可以调用HibernateTemplate的execute(HibernateCallBack callBack)来编写原始hibernate代码来进行查询。
数据库操作重要的一点是事务,spring事务的说明请见下面的文章。
使用spring管理事务后,我们将不用手工编写事务代码。
下面我们看一下具体的实现
说一下大体的结构
HelloWorld Action(Struts Action 对象,由spring管理,具体方法见下文:)
调用业务对象personbean的saveToPersistentStore方法去进行持久化操作。saveToPersistentStore中通过调用UserDAO去进行持久化操作
我们看一下这三个类的源码:
Action:
package com.hf.struts.sayHello;
 
 
import javax.servlet.http.HttpServletRequest;
 
import javax.servlet.http.HttpServletResponse;
 
import org.apache.struts.action.Action;
 
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
 
 
import com.hf.bean.sayHello.PersonBean;
 
public final class HelloAction extends Action {
       PersonBean pb = null;
    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.
     */
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        String userName = (String)((HelloForm) form).getUserName();
        pb.setUserName(userName);
        int times=pb.saveToPersistentStore();
        request.setAttribute( "personbean", pb);
        request.setAttribute("times",String.valueOf(times));
        //request.setAttribute("times",String.valueOf(1));
        request.removeAttribute(mapping.getAttribute());
        return (mapping.findForward("displayHello"));
 
    }
       public PersonBean getPb() {
              return pb;
       }
       public void setPb(PersonBean pb) {
              this.pb = pb;
       }
}
 
 
 
Personbean:

package com.hf.bean.sayHello;
 
import com.hf.dao.sayHello.UserDAO;
import com.hf.hibernate.pojo.User;
 
public class PersonBean {
       private UserDAO userDAO=null;
 
    private String userName = "";
 
    public String getUserName() {
        return this.userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    /**
     * This is a stub method that would be used for the Model to save
     * the information submitted to a persistent store. In this sample
     * application it is not used.
     * @return
     */
    public int saveToPersistentStore() {
            
       
         User user=userDAO.getUserByName(this.getUserName());
         if(user==null){
                return userDAO.saveUser(this.getUserName());
         }else{
                return userDAO.updateUser(user.getId());
         }
        
       
    }
       public UserDAO getUserDAO() {
              return userDAO;
       }
       public void setUserDAO(UserDAO userDAO) {
              this.userDAO = userDAO;
       }
}
 
 
UserDAO:
 

package com.hf.dao.sayHello;
 
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.hf.hibernate.pojo.User;
import com.hf.util.sequence.IDGenerator;
 
 
 
publicclass UserDAO extends HibernateDaoSupport {
 
    public User getUserByName(String name){
       
        try{
        if(name!=null){
           List list =this.getHibernateTemplate().find("from User user where user.name=?",name);
           if(list!=null&&list.size()==1){
                User user=(User) list.get(0);
                return user;
            }
        }
        }catch(Exception e){
            e.printStackTrace();
        }
        finally{
           
           
        }
        //���?вѯ���