.spring配置 
配置文件为applicationContext-hibernate.xml,在此配置文件中,配了POJO层,商业逻辑层,DAO层,和事务管理 
java代码:  
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans>        
        <!-- ========================= Start of PERSISTENCE DEFINITIONS ========================= -->  
        
        <!-- Choose the dialect that matches your "dataSource" definition -->         <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
                <property name="driverClassName"> 
                        <value>org.gjt.mm.mysql.Driver</value> 
                </property> 
                <property name="url"> 
                        <value>jdbc:mysql://localhost:3306/info_web?useUnicode=true&characterEncoding=GBK</value> 
                </property> 
                <property name="username"> 
                        <value>root</value> 
                </property> 
                <property name="password"> 
                        <value>123456</value> 
                </property> 
        </bean> 
        
        <bean id="mySessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean"> 
                <property name="mappingResources"> 
                        <list> 
                                <value>infoweb/pojo/Answer.hbm.xml</value> 
                                <value>infoweb/pojo/Board.hbm.xml</value> 
                                <value>infoweb/pojo/Image.hbm.xml</value> 
                                <value>infoweb/pojo/Info.hbm.xml</value> 
                        </list> 
                </property>                
                
                <property name="hibernateProperties"> 
                        <props> 
                                <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop> 
                                <prop key="hibernate.show_sql">true</prop> 
                                <prop key="hibernate.cglib.use_reflection_optimizer">true</prop> 
                        </props> 
                </property>                        <property name="dataSource"><ref bean="myDataSource"/></property> 
        </bean>         <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --> 
        <bean id="myTransactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"> 
                <property name="sessionFactory"><ref local="mySessionFactory"/></property> 
        </bean> 
                <!-- ***** Board  SERVICE ***** --> 
        <bean id="boardService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">        
                <property name="transactionManager"><ref local="myTransactionManager"/></property> 
                <property name="target"><ref local="boardServiceSpring"/></property> 
                <property name="transactionAttributes"> 
                        <props> 
                                <prop key="get*">PROPAGATION_REQUIRED,readOnly,-BoardException</prop> 
                                <prop key="set*">PROPAGATION_REQUIRED,-BoardException</prop> 
                                <prop key="modify*">PROPAGATION_REQUIRED,-BoardException</prop> 
                                <prop key="remove*">PROPAGATION_REQUIRED,-BoardException</prop> 
                        </props> 
                </property> 
        </bean>         <!-- board primary business object implementation --> 
        <bean id="boardServiceSpring" class="infoweb.service.BoardServiceSpringImpl"> 
                <property name="boardTreeDAO"><ref local="boardTreeDAO"/></property> 
        </bean> 
                <!-- DAO board: Hibernate implementation --> 
        <bean id="boardTreeDAO" class="infoweb.dao.BoardTreeDAOImpl"> 
                <property name="sessionFactory"><ref local="mySessionFactory"/></property> 
        </bean>         <!-- DAO info: Hibernate implementation --> 
        <bean id="infoDAO" class="infoweb.dao.InfoDAOImpl"> 
                <property name="sessionFactory"><ref local="mySessionFactory"/></property> 
        </bean> 
</beans> 
 

解决方案 »

  1.   

    3.做DAO代码, 
    java代码:  
    package infoweb.dao; import java.util.List; 
    import java.util.Iterator; import infoweb.pojo.Board; 
    import net.sf.hibernate.HibernateException; 
    import net.sf.hibernate.Query; 
    import net.sf.hibernate.Session; import org.springframework.orm.hibernate.HibernateCallback; 
    import org.springframework.orm.hibernate.support.HibernateDaoSupport; 
    /** 
    * <p>Title: 版块分类DAOImpl</p> 
    * <p>Description: 用树型结构实现</p> 
    * <p>Copyright: Copyright (c) 2004</p> 
    * <p>Company: </p> 
    * @author 段洪杰 
    * @version 1.0 
    */ 
    public class BoardTreeDAOImpl extends HibernateDaoSupport implements 
        IBoardTreeDAO { 
      /** 
       * 构造函数 
       */ 
      public BoardTreeDAOImpl() { 
        super(); 
      } 
      /** 
       * 通过ID取得版块 
       * @param id String 
       * @return Board 
       */   public Board getBoardById(String id) { 
        Board board = (Board) getHibernateTemplate().load(Board.class, id); 
        return board; 
      } 
      /** 
       * 取根叶 
       * @return Iterator 
       */ 
      public Iterator getRoots() throws HibernateException { 
        String queryString = 
            "select board from Board as board where board.parentId='root' order by board.id desc"; 
        List roots = getHibernateTemplate().find(queryString); 
        return roots.iterator(); 
      } 
      /** 
       * 存根叶 
       * @param board Board 
       */ 
      public void setRoot(Board board) { 
        board.setParentId("root"); 
        getHibernateTemplate().save(board); 
      } 
      /** 
       * 取子叶 
       * @param  parentid String 
       * @return List 
       */ 
      public Iterator getChildren(String parentid) { 
        /* 
             String queryString = 
         "select board as Board where board.parent_id='parentid' order by board.id desc"; 
             List children = getHibernateTemplate().find(queryString); 
             return children; 
         */ 
        Board parent = (Board) getHibernateTemplate().load(Board.class, parentid); 
        return parent.getChildren().iterator(); 
      } 
      /** 
       * 取子叶数 
       * @param parentid String 
       * @return int 
       */   public int getChildrenCount(String parentid) { 
        /* 
             String queryString = 
         "select count(*) Board where board.parent_id='parentid' order by board.id desc"; 
             List children = getHibernateTemplate().find(queryString); 
             int count = ((Integer) children.iterator().next()).intValue(); 
             return count; 
         */ 
        Board parent = (Board) getHibernateTemplate().load(Board.class, parentid); 
        int count = parent.getChildren().size(); 
        return count; 
      } 
      /** 
       * 存子叶 
       * @param parentLeaf Leaf 
       */ 
      public void setChild(Board board, String parentid) { 
        board.setParentId(parentid); 
        getHibernateTemplate().save(board); 
      } 
      /** 
       * 
       * 删除该叶和它的子叶 
       * @param board Board 
       */ 
      public void deleteBranch(Board board) { 
          getHibernateTemplate().delete(board); 
      } 
      /** 
       * 根据子叶得到父叶 
       * @param child Board 
       * @return Board 
       */ 
      public Board getParentByChild(Board child) { 
        String parentId = child.getParentId(); 
        Board parent = (Board) getHibernateTemplate().load(Board.class, parentId); 
        return parent; 
      } 
      /** 
       * 通过子ID得到父叶 
       * @param id String 
       * @return Board 
       */ 
      public Board getParentByChildId(String id) { 
        Board child = (Board) getHibernateTemplate().load(Board.class, id); 
        Board parent = (Board) getHibernateTemplate().load(Board.class,child.getParentId()); 
        return parent; 
      } 

     
    4.做service层代码 java代码:  
    package infoweb.service; import java.util.List; 
    import java.util.Iterator; 
    import infoweb.dao.BoardTreeDAOImpl; 
    import infoweb.dao.IBoardTreeDAO; 
    import infoweb.pojo.Board; 
    import infoweb.exception.BoardException; 
    import net.sf.hibernate.HibernateException; /** 
    * <p>Title: </p> 
    * <p>Description: </p> 
    * <p>Copyright: Copyright (c) 2004</p> 
    * <p>Company: </p> 
    * @author 段洪杰 
    * @version 1.0 
    */ 
    public class BoardServiceSpringImpl implements IBoardService {     private IBoardTreeDAO boardTreeDAO;     public BoardServiceSpringImpl() { 
            super(); 
        }     /** 
         * 取所有roots版块 
         * @return Iterator 
         */ 
        public Iterator getRoots() throws BoardException { 
            Iterator roots = null; 
            try { 
                roots = boardTreeDAO.getRoots(); 
            } catch (Exception ex) { 
                throw new BoardException("取ROOT版块时出错! " + ex.toString()); 
            } 
            return roots; 
        }     /** 
         * 增加Root新版块 
         * @param board Board 
         */ 
        public void setRoot(Board board) throws BoardException { 
            try { 
                boardTreeDAO.setRoot(board); 
            } catch (Exception ex) { 
                throw new BoardException("增加ROOT版块时出错! " + ex.toString()); 
            } 
        }     /** 
         * 删除版块 (包含下级版块) 
         * @param board Board 
         */ 
        public void removeBoard(Board board) throws BoardException { 
            try { 
                boardTreeDAO.deleteBranch(board); 
            } catch (Exception ex) { 
                throw new BoardException("删除版块时出错! " + ex.toString()); 
            } 
        }     /** 
         * 
         * @return IBoardTreeDAO 
         */ 
        public IBoardTreeDAO getBoardTreeDAO() { 
            return boardTreeDAO; 
        }     /** 
         * 
         * @param boardTreeDAO IBoardTreeDAO 
         */ 
        public void setBoardTreeDAO(IBoardTreeDAO boardTreeDAO) { 
            this.boardTreeDAO = boardTreeDAO; 
        } } 
     
      

  2.   

    5.做ACTION的父类 java代码:  
    package infoweb.web; 
    import javax.servlet.ServletContext; 
    import org.apache.struts.action.Action; 
    import org.apache.struts.action.ActionServlet; 
    import org.springframework.web.context.WebApplicationContext; 
    import org.springframework.web.context.support.WebApplicationContextUtils; import infoweb.service.IBoardService; 
    /** 
    * <p>Title: </p> 
    * <p>Description: </p> 
    * <p>Copyright: Copyright (c) 2004</p> 
    * <p>Company: </p> 
    * @author 段洪杰 
    * @version 1.0 
    */ public class BaseAction extends Action {   private IBoardService boardService;   public void setServlet(ActionServlet actionServlet) { 
        super.setServlet(actionServlet); 
        ServletContext servletContext = actionServlet.getServletContext(); 
        WebApplicationContext wac = 
            WebApplicationContextUtils.getRequiredWebApplicationContext( 
            servletContext); 
        this.boardService = (IBoardService) wac.getBean("boardService"); 
      }   protected IBoardService getBoardService() { 
        return boardService; 
      } } 
     
    6.做action类 
    java代码:  
    package infoweb.web; import infoweb.pojo.Board; 
    import org.apache.commons.beanutils.PropertyUtils; 
    import org.apache.struts.action.*; 
    import org.apache.log4j.Logger; 
    import javax.servlet.http.*; 
    import java.util.Iterator; 
    import java.util.Date; /** 
    * <p>Title: </p> 
    * <p>Description: </p> 
    * <p>Copyright: Copyright (c) 2004</p> 
    * <p>Company: </p> 
    * @author 段洪杰 
    * @version 1.0 
    */ 
    public class SetBoardAction extends BaseAction {     private static Logger log = Logger.getLogger(SetBoardAction.class);     public ActionForward execute(ActionMapping actionMapping, 
                                     ActionForm actionForm, 
                                     HttpServletRequest httpServletRequest, 
                                     HttpServletResponse httpServletResponse) throws 
                Exception {         // SessionBean sessionBean = (SessionBean) httpServletRequest.getSession().getAttribute("sessionBean"); 
            BoardForm boardForm = (BoardForm) actionForm; 
            //String backURL = httpServletRequest.getHeader("Referer"); 
            /* 
            if (sessionBean==null||!sessionBean.getIsLogon()) { 
                httpServletRequest.setAttribute("message", "系统超时,或者没有登录 .返回重新登录!"); 
                httpServletRequest.setAttribute("locationFile", 
                                                "location='index.jsp';"); 
                return actionMapping.findForward("message"); 
            } 
            */ 
            Board board = new Board(); 
            boardForm.setCreateDate(new Date()); 
            PropertyUtils.copyProperties(board, boardForm); 
            getBoardService().setRoot(board);         httpServletRequest.setAttribute("message", "版块信息录入完成!"); 
            httpServletRequest.setAttribute("locationFile", 
                                            "<A HREF=\"javascript:history.back()\">返回</A>"); 
            return (actionMapping.findForward("success")); 
        } } 
     
      

  3.   

    可运行的增删查改的hibernate小例子(用oracle数据库的dept表)
    (1)引进hibernate-2.1.2\hibernate-2.1\lib下的所有文件和hibernate-2.1.2\hibernate-2.1\hibernate2.jar文件
    (2)引进数据库驱动文件
    (3)把Dept.hbm.xml和hibernate.cfg.xml文件手动放在classes下边
    (4)Dept.hbm.xml
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping
      PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
      "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
    <hibernate-mapping>
    <class name="zhaoqingjie.Dept" table="dept">
      <id name="deptno" type="integer" unsaved-value="0">
        <generator class="assigned"/>
      </id>
      <property name="dname"/>
      <property name="loc"/>
    </class>
    </hibernate-mapping>
    (5)hibernate.cfg.xml
    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-configuration
      PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
      "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
    <hibernate-configuration>
    <session-factory>
      <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
      <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
      <property name="hibernate.connection.username">scott</property>
      <property name="hibernate.connection.password">tiger</property>
      <property name="dialect">net.sf.hibernate.dialect.Oracle9Dialect</property>
      <!-- Mapping files -->
      <mapping resource="Dept.hbm.xml"/>
    </session-factory>
    </hibernate-configuration>
    (6)Dept.java
    package zhaoqingjie;/**
    * <p>Title: </p>
    *
    * <p>Description: </p>
    *
    * <p>Copyright: Copyright (c) 2005</p>
    *
    * <p>Company: </p>
    *
    * @author zhaoqingjie
    * @version 1.0
    */
    public class Dept {
      private int deptno;
      private String dname;
      private String loc;
      public int getDeptno() {
        return deptno;
      }  public String getDname() {
        return dname;
      }  public String getLoc() {
        return loc;
      }  public void setLoc(String loc) {
        this.loc = loc;
      }  public void setDname(String dname) {
        this.dname = dname;
      }  public void setDeptno(int deptno) {
        this.deptno = deptno;
      }}
    (7)Hibernate.java
    package zhaoqingjie;import net.sf.hibernate.*;
    import net.sf.hibernate.cfg.*;
    import net.sf.hibernate.cfg.Configuration.*;
    /**
    * <p>Title: </p>
    *
    * <p>Description: </p>
    *
    * <p>Copyright: Copyright (c) 2005</p>
    *
    * <p>Company: </p>
    *
    * @author zhaoqingjie
    * @version 1.0
    */
    public class HibernateUtil {
      public HibernateUtil() {
        try {
            jbInit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
      }  private static final SessionFactory sessionFactory;
      static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (HibernateException ex) {
            throw new RuntimeException("Exception building SessionFactory: " +
                              ex.getMessage(), ex);
        }
      }  private static final ThreadLocal session = new ThreadLocal();  public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
      }  public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null) {
            s.close();
        }
      }  private void jbInit() throws Exception {
      }
    }
    (8)Hibernate.java
    package zhaoqingjie;import java.sql.Date;
    import java.util.Iterator;
    import net.sf.hibernate.*;
    import net.sf.hibernate.Query;
    import net.sf.hibernate.Session;
    import net.sf.hibernate.Transaction;/**
    * <p>Title: </p>
    *
    * <p>Description: </p>
    *
    * <p>Copyright: Copyright (c) 2005</p>
    *
    * <p>Company: </p>
    *
    * @author zhaoqingjie
    * @version 1.0
    */
    public class Hibernate {
      public static void main(String[] args) {
        try {
            Session session = HibernateUtil.currentSession();
            Transaction tx = session.beginTransaction();
            
            /*insert
                    Dept dept = new Dept();
                    dept.setDeptno(60);
                    dept.setDname("公安部");
                    dept.setLoc("北京");
                    session.save(dept);
            */
            
            //select
            Query query = session.createQuery("select dept from Dept as dept");
            Iterator it = query.iterate();
            while (it.hasNext()) {
              Dept dept = (Dept)it.next();
              System.out.println("deptno = " + dept.getDeptno());
              System.out.println("dname = " + dept.getDname());
              System.out.println("loc = " + dept.getLoc());
            }
            
          
          /*update
            Dept dept = (Dept) session.load(Dept.class, new Integer(50));
            dept.setDname("AA");
            session.update(dept);
          */
          
          /*delete
            Dept dept = (Dept) session.load(Dept.class, new Integer(50));
            dept.setDname("AA");
            session.delete(dept);
          */
            tx.commit();
            HibernateUtil.closeSession();
        } catch (HibernateException ex) {
            ex.printStackTrace(System.out);
        }
      }
    }