java開發中使用spring+hibernate+struts

來源:互聯網
上載者:User

  sping是個好東西,可還是喜歡struts的MVC,一部分原因是以前做的項目都是struts的使用習慣了,第二目前從使用者數來說還是struts的最多,但sping與struts也並不是相排斥的可以結合著使用,相比而言現在另一熱門的架構技術Tapestry還真覺得有點排它性,Tapestry也是不錯,但相比struts而言學習門檻要高得多,學習資料也少,目前使用Tapestry技術的公司也比較少。


  sping中整合了hibernate的交易管理,這個偶比較喜歡,可以少寫好多代碼耶。主要是用到以下這幾個類吧:
   import org.springframework.orm.hibernate.HibernateCallback;
   import org.springframework.orm.hibernate.SessionFactoryUtils;
   import org.springframework.orm.hibernate.support.HibernateDaoSupport;
大家可以先寫一個hibernate基礎工具類,然後各使用到的類繼承它,差不多實用的方法都在裡面了。


import java.util.Collection;
import java.util.Iterator;
import java.util.List;


import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import net.sf.hibernate.Session;
import net.sf.hibernate.type.Type;


import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate.HibernateCallback;
import org.springframework.orm.hibernate.SessionFactoryUtils;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;


public class BaseDAO extends HibernateDaoSupport{
 
 public BaseDAO(){
  super();
 }
 
   public void clear() throws DataAccessException
   {
     getHibernateTemplate().clear();
   }


   public void flush() throws DataAccessException
   {
     getHibernateTemplate().flush();


   }


   public int countByNamedQuery(final String queryName, final Object[] values)
       throws DataAccessException
   {
     String str = getQueryString(queryName);
     str = getCountString(str);
     return ((Integer) getHibernateTemplate().find(str, values).get(0))
         .intValue();
   }


   public int countByNamedQueryAndNamedParam(final String queryName,
       final String[] paramNames, final Object[] values)
       throws DataAccessException
   {
     String str = getQueryString(queryName);
     str = getCountString(str);
     return ((Integer) getHibernateTemplate().findByNamedParam(str, paramNames,
         values).get(0)).intValue();
   }


   public int delete(String queryString, Object value, Type type)
       throws DataAccessException
   {
     return getHibernateTemplate().delete(queryString, value, type);
   }


   public void deleteAll(Collection entities) throws DataAccessException
   {
     getHibernateTemplate().deleteAll(entities);


   }


   public List find(String queryString, Object[] values)
       throws DataAccessException
   {
     return getHibernateTemplate().find(queryString, values);
   }


   public List findByNamedParam(String queryString, String[] paramNames,
       Object[] values) throws DataAccessException
   {
     return getHibernateTemplate().findByNamedParam(queryString, paramNames,
         values);
   }


   public List findByNamedQuery(String queryName, Object value)
       throws DataAccessException
   {
     return getHibernateTemplate().findByNamedQuery(queryName, value);
   }


   public List findByNamedQuery(String queryName, Object[] values)
       throws DataAccessException
   {
     return getHibernateTemplate().findByNamedQuery(queryName, values);
   }


   public List findByNamedQueryAndValueBean(String queryName, Object valueBean)
       throws DataAccessException
   {
     return getHibernateTemplate().findByNamedQueryAndValueBean(queryName,
         valueBean);
   }


   public List findPage(final String queryString, final Object value,
       final int firstResult, final int maxResults) throws DataAccessException
   {
     return getHibernateTemplate().executeFind(new HibernateCallback()
     {


       public Object doInHibernate(Session session) throws HibernateException
       {
         Query query = session.createQuery(queryString);
         query.setParameter(0, value);
         query.setFirstResult(firstResult);
         query.setMaxResults(maxResults);
         return query.list();


       }
     });
   }


   public List findPageByNamedQuery(final String queryName, final Object value,
       final int firstResult, final int maxResults) throws DataAccessException
   {
     return getHibernateTemplate().executeFind(new HibernateCallback()
     {


       public Object doInHibernate(Session session) throws HibernateException
       {
         Query query = session.getNamedQuery(queryName);
         query.setParameter(0, value);
         query.setFirstResult(firstResult);
         query.setMaxResults(maxResults);
         return query.list();


       }
     });
   }


   public Iterator iterate(String queryString) throws DataAccessException
   {
     return getHibernateTemplate().iterate(queryString);
   }


}
要使用sping中hibernate的交易管理還得要在applicationContext.xml這個設定檔中設定一下,舉個簡單的例子:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!-- $Id: uum-applicationContext.xml,v 1.2 2005/09/21 09:24:09 wj Exp $ -->
<beans>
  <!--
    Datasource that works in any application server
    You could easily use J2EE data source instead if this were
    running inside of a J2EE container.
  -->
  <!--bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:comp/env/jdbc/uumDataSource</value>
        </property>
  </bean-->
 
  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName">
      <value>oracle.jdbc.driver.OracleDriver</value>
    </property>
    <property name="url">
      <value>jdbc:oracle:thin:@127.0.0.1:1521:demo</value>
    </property>


    <property name="username">
      <value>spuser</value>
    </property>
    <property name="password">
      <value>123456</value>
    </property>
  </bean>
  <!-- Hibernate SessionFactory -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
    <property name="dataSource">
      <ref local="dataSource"/>
    </property>
    <!-- Must references all OR mapping files. -->
    <property name="mappingResources">
      <list>
        <value>pojo/FujianInfo.hbm.xml</value>
  <value>pojo/SpInfo.hbm.xml</value>
  <value>pojo/User.hbm.xml</value>
      </list>
    </property>
    <!--
      Set the type of database; changing this one property will port this to Oracle,
      MS SQL etc.
    -->
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">net.sf.hibernate.dialect.Oracle9Dialect</prop>
        <prop key="hibernate.query.substitutions">true 1,false 0</prop>
        <prop key="hibernate.jdbc.fetch_size">50</prop>
        <prop key="hibernate.jdbc.batch_size">0</prop>
        <prop key="hibernate.show_sql">true</prop>
      </props>
    </property>
  </bean>
  <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
  <bean id="iserviceTarget" class="service.spring.Service" singleton="false">
 <property name="userDAO">
      <ref local="userDAO"/>
    </property>
    <property name="spInfoDAO">
      <ref local="spInfoDAO"/>
    </property>
 <property name="fujianInfoDAO">
      <ref local="fujianInfoDAO"/>
    </property>
  </bean>
  <!-- Transactional proxy for the Petclinic primary business object -->
  <bean id="iservice" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager">
      <ref local="transactionManager"/>
    </property>
    <property name="target">
      <ref local="iserviceTarget"/>
    </property>
    <property name="transactionAttributes">
      <props>
        <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
        <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
        <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
        <prop key="insert*">PROPAGATION_REQUIRED</prop>
        <prop key="store*">PROPAGATION_REQUIRED</prop>
        <prop key="appand*">PROPAGATION_REQUIRED</prop>
        <!--prop key="add*">PROPAGATION_REQUIRED</prop-->
        <prop key="save*">PROPAGATION_REQUIRED</prop>
        <prop key="update*">PROPAGATION_REQUIRED</prop>
        <prop key="remove*">PROPAGATION_REQUIRED</prop>
        <prop key="delete*">PROPAGATION_REQUIRED</prop>
        <prop key="count*">PROPAGATION_REQUIRED</prop>
        <prop key="is*">PROPAGATION_REQUIRED</prop>
      </props>
    </property>
  </bean>
  <!-- Pass the session factory to our DAOs -->
  <bean id="userDAO" class="dao.hibernate.UserDAO">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
  <bean id="fujianInfoDAO" class="dao.hibernate.FujianInfoDAO">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
  <bean id="spInfoDAO" class="dao.hibernate.SpInfoDAO">
    <property name="sessionFactory">
      <ref local="sessionFactory"/>
    </property>
  </bean>
</beans>
將要用到交易管理的持久類作為bean往
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">這一段裡添加。
將這個檔案放在class根目錄下系統起動時會自動載入,也可以自己手動控制載入。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.