spring應用樣本

來源:互聯網
上載者:User
       spring中對hibernate的支援是非常強大的,從一個簡單的例子就看得出來,從這個例子中我們還將對所謂的輕量級容器做一些討論。

  首先需要配置資料來源,通常我們有兩種方式獲得Connection,一是自己編寫代碼獲得串連,二是從JNDI環境中得到DataSource,然後產生一個Connection。無論怎樣,既然是spring下面的對象,就應該註冊到設定檔中。假設我們需要一個串連mysql下面一個叫做examer的資料庫,手動方式的配置是:

  1. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  2.   <property name="driverClassName">
  3.     <value>com.mysql.jdbc.Driver</value>
  4.   </property>
  5.   <property name="url">
  6.     <value>jdbc:mysql://localhost/examer</value>
  7.   </property>
  8.   <property name="username">
  9.     <value>root</value>
  10.   </property>
  11.   <property name="password">
  12.     <value></value>
  13.   </property>
  14. </bean>

  很好讀是不是?假如我們使用JNDI資料來源,那麼dataSource的聲明就應該是:

  1. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
  2.   <property name="jndiName">
  3.     <value>java:compenvjdbcspringExamer</value>
  4.   </property>
  5. </bean>

  你需要在JNDI環境中綁定一個名為jdbc/springExamer的東西,這段代碼才有實際意義。另外需要提醒的是,所有的bean聲明,它的id必須是唯一的。

  在本系統中,資料庫操作是被hibernate封裝起來的,所以dataSource是不需要注入到具體的邏輯類中,它只會被注給hibernate的sessionFactory。

  按照常規思路,我們需要在spring中註冊hibernate的sessionFactory,它應該是我們自己編寫的一個類,獲得dataSource,返回sessionFactory,其他的邏輯類通過這個sessionFactory獲得session進行資料庫操作。

  但是我們有另外一種選擇,spring直接提供了對sessionFactory的封裝,你只需要註冊一個spring自己的類,給它提供必須的屬性,它會返回一個org.springframework.orm.hibernate.HibernateTemplate,這個類封裝了add、del等操作,它的封裝程度相當高,通過它來編寫hibernate應用非常簡單。但是問題出來了,我們該如何選擇?

  表面上看,使用spring自己的庫無疑更加簡單,但是請注意,spring是一個輕量級的架構,所謂輕量級,一個重要特徵就是無侵入性,也就是你使用這套架構,不會被它綁定,被spring管理的類,應該不需要使用它的介面和抽象類別,這樣你的系統不會對spring產生依賴。但是如果你使用了spring封裝的方式去操作hibernate,就必須繼承org.springframework.orm.hibernate.support.HibernateDaoSupport類,這導致了綁定。所以做這樣的選擇是有點痛苦的,如果有一天spring架構不存在了,你的代碼怎麼升級維護?具體問題只能具體分析,在我們的應用中,完全使用了spring封裝的HibernateTemplate,它太好用了,所以容易上癮。

  假設我們有一張student表,結構很簡單:

  

  1. id      自動成長
  2.   name     varchar(40)
  3.   password   varchar(32)
  4.   grade        int(4)      年級
  5.   sex     Boolean      性別(true為男,false為女)

  設計一個Student類來映射這張表:

  1. /*
  2.  * 建立日期 2005-3-17
  3.  */
  4. package net.bromon.spring.examer.pojo;
  5.  
  6. /**
  7.  * @author Bromon
  8.  */
  9. public class Student 
  10. {
  11.     private int id;
  12.     private String name;
  13.     private String password;
  14.     private int grade;//年級
  15.     private boolean sex;
  16.     
  17.     getset方法……….
  18. }

  編寫Student.hbm.xml,讓hibernate知道如何去關聯student表和Student類,該檔案和Student.java在同一目錄:

  1. <hibernate-mapping>
  2.   <class name="net.bromon.spring.examer.pojo.Student" table="student">
  3.     <id name="id" column="id">
  4.       <generator class="identity"/>
  5.     </id>
  6.         
  7.     <property name="name" column="name" />
  8.     <property name="password" column="password" />
  9.     <property name="grade" column="grade" />
  10.     <property name="sex" column="sex" />
  11.   </class>
  12. </hibernate-mapping>

  然後我們可以在spring中配置sessionFactory:

  1. <bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
  2.   <property name="dataSource">
  3.     <ref bean="dataSource"/>
  4.   </property>
  5.         
  6.   <property name="hibernateProperties">
  7.     <props>
  8.       <prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
  9.     </props>
  10.   </property>
  11.         
  12.   <property name="mappingDirectoryLocations">
  13.     <list>
  14.       <value>classpath:/netbromonspringexamerpojo</value>
  15.     </list>
  16.   </property>
  17. </bean>

  其中引用了我們之前註冊過的dataSource,mappingDirectoryLocations屬性指明了.hbm.xml檔案在哪裡路徑,該檔案夾下面的.hbm.xml檔案會被全部載入。

  一切都準備就緒,現在我們要加入一個StudentManager類,來進行增刪查改的操作:

  1. /*
  2.  * 建立日期 2005-3-17
  3.  */
  4. package net.bromon.spring.examer.student;
  5.  
  6. import net.bromon.spring.examer.pojo.Student;
  7.  
  8. import org.springframework.orm.hibernate.HibernateTemplate;
  9. import org.springframework.orm.hibernate.LocalSessionFactoryBean;
  10. import org.springframework.orm.hibernate.support.HibernateDaoSupport;
  11.  
  12. /**
  13.  * @author Bromon
  14.  */
  15. public class StudentManager extends HibernateDaoSupport
  16. {
  17.     private LocalSessionFactoryBean sessionFactory;
  18.     private HibernateTemplate ht;
  19.     public StudentManager()
  20.     {
  21.         this.ht=super.getHibernateTemplate();
  22.     }
  23.     
  24.     public void add(Student s)
  25.     {   
  26.         ht.save(s);//插入一條資料只需要這一行代碼
  27.     }
  28. }

  該類只示範了如何增加一個Student,HibernateTemplate還封裝了很多有用的方法,請查閱spring文檔。StudentManager中的sessionFactory是由spring注入的,但是StudentManager並沒有對sessionFactory做任何的處理,這是因為所有的處理都被HibernateDaoSupport.getHibernateTemplate()封裝。整個StudentManager中也看不到任何的異常處理,他們也都被基類封裝了。

  最後一個步驟就是在spring中註冊StudentManger,然後向它注入sessionFactory:

  1. <bean id="studentManager" class="net.bromon.spring.examer.student.StudentManager">
  2.   <property name="sessionFactory">
  3.     <ref bean="sessionFactory"/>
  4.   </property>
  5. </bean>

  所有的配置都完成了,下面做單元測試:

  1. /*
  2.  * 建立日期 2005-3-17
  3.  */
  4. package net.bromon.spring.examer.student.test;
  5.  
  6. import java.io.FileInputStream;
  7.  
  8. import org.springframework.beans.factory.xml.XmlBeanFactory;
  9. import org.springframework.context.ApplicationContext;
  10. import org.springframework.context.support.ClassPathXmlApplicationContext;
  11.  
  12. import net.bromon.spring.examer.pojo.Student;
  13. import net.bromon.spring.examer.student.StudentManager;
  14. import junit.framework.TestCase;
  15.  
  16. /**
  17.  * @author Bromon
  18.  */
  19. public class TestStudentManager extends TestCase {
  20.  
  21.     public void testAdd() 
  22.     {
  23.         try
  24.         {
  25.             ApplicationContext context =new ClassPathXmlApplicationContext("springConfig.xml");
  26.             
  27.             Student s=new Student();
  28.             s.setName("bromon");
  29.             s.setPassword("123");
  30.             s.setGrade(3);
  31.             s.setSex(true);
  32.             
  33.             ((StudentManager)context.getBean("studentManager")).add(s);
  34.         }catch(Exception e)
  35.         {
  36.             e.printStackTrace();
  37.         }
  38.     }
  39.  
  40. }

  Spring已經將hibernate的操作簡化到了非常高的程度,最關鍵的是整個開發可以由設計來驅動,如果一個團隊對spring有足夠的熟悉,那麼完全可以由設計師規劃所有的類,整理清楚類之間的關係,寫成設定檔,然後編寫hibernate對應檔,將資料表與pojo關聯,成員就可以完全在設計方案內工作,利用spring封裝好的hibernate模版,開發起來速度非常快,調試也很容易。它能夠解決如何在團隊內貫徹設計方案的問題。

  由於本文不講解hibernate的使用,所以相關內容請查閱hibernate文檔。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.