spring 整合 jdbc 具體實現

一、整合的步驟

  1、步驟一:首先要獲得DataSource連接池(推薦使用B方式):
要對數據庫執行任何的JDBC操作,需要有一個Connection.在Spring中,Connection對象是通過DataSource獲得的。

有幾種方法可以得到DataSource, 其中一種方法是使用Spring提供的輕量級org.springframework.jdbc.datasource.DriverManagerDataSource,第二種方法是使用org.apache.commons.dbcp.BasicDataSource類。

  A:使用DriverMangerDataSource獲取DataSource,這種方法是輕量級的,方便測試
    public class DataSoureProvider {
     public static DriverManagerDataSource dataSource = new DriverManagerDataSource();
 
     public static DriverManagerDataSource getInstance() {
         dataSource.setDriverClassName("com.mysql.jdbc.Driver");
         dataSource.setUrl("jdbc:mysql://localhost:3306/book");
         dataSource.setUsername("y****");
         dataSource.setPassword("h*******");
         return dataSource;
     }
 
     @Test
     public void test() {
         DataSoureProvider.getInstance();
         try {
             dataSource.getConnection();
         }
         catch (SQLException e) {
             e.printStackTrace();
         }
     }
 }

  B:通過使用BasicDataSouce創建一個連接池
獲取DataSource應爲BasicDataSource所有屬性都是通過setter方法暴露在外面的,我們可以像配置其他Srping Bean那樣配置它我將數據庫連接信息配置在properties文件中,利用spring的org.springframeword.beans.factory.config.PropertyPlaceholderConfigurer類進行讀取裝載。
注意:

使用org.apache.commons.dbcp.BasicDataSource需要引入額外的jar包,分別是,commons-dbcp-1.4.jar,commons-pool-1.2.jar (官網下載頁面:http://commons.apache.org/) 

    書寫配置文件applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
 <beans
     xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:p="http://www.springframework.org/schema/p"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
     <bean id="dbproperty" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="location">

             <!-- 此位置是相對於:部署後的項目的根路徑
              <value>/WEB-INF/
connect.properties</value> -->
             <!-- 此位置是相對於:部署後的項目的類路徑 -->               <value>connect.properties</value>
         </property>
     </bean>
     <-- 配置BasicDataSource參數,其中<value>中的參數是在connect.propertices配置文件 中拿到的,其實value值也可以直接寫上的-->
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
         <property name="driverClassName">
             <value>${db.driver}</value>
         </property>
         <property name="url">
             <value>${db.url}</value>
         </property>
         <property name="username">
             <value>${db.username}</value>
         </property>
         <property name="password">
             <value>${db.password}</value>
         </property>
     </bean>

 </beans>

--------------------------------------------------------------------------------------

  2、步驟二:使用JdbcTemplate類操作數據庫:
    Spring把JDBC中重複的操作建立成了一個模板類:org.springframework.jdbc.core.JdbcTemplate。
   A:要使用JdbcTemplate,需要爲每一個DAO配置一個JdbcTemplate實例:
  public class StudentDaoImp implements StudentDao {
     private JdbcTemplate jdbcTemplate;
 
     @Override
     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
         this.jdbcTemplate = jdbcTemplate;
     }
 }
  B:如上,StudentDaoImp內配置了一個JdbcTemplate對象和它對應的setter方法。這樣就可以在Spring配置文件中對其進行賦值。
<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
     <bean id="dbproperty"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="location">
             <value>connect.properties</value>
         </property>
     </bean>
 
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
         <property name="driverClassName">
             <value>${db.driver}</value>
         </property>
         <property name="url">
             <value>${db.url}</value>
         </property>
         <property name="username">
             <value>${db.username}</value>
         </property>
         <property name="password">
             <value>${db.password}</value>
         </property>
     </bean>
 
     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
         <constructor-arg ref="
myDataSource"></constructor-arg>
     </bean>

    
     <bean id="studentDao" class="com.sunflower.dao.StudentDaoImp">
         <property name="jdbcTemplate">
             <ref bean="jdbcTemplate"/>
         </property>
     </bean>
 </beans>
  C:使用JdbcTemplate插入數據:
   

   1)插入單條數據:JdbcTemplate爲我們提供了update(String sql,Object... args)方法,方便我們進行數據的插入.
 
  2)批量添加數據:批量插入數據需要用到org.springframework.jdbc.core.BatchPreparedStatementSetter接口。BatchPreparedStatementSetter接口的兩個方法,其中getBatchSize()方法是得到需要插入的記錄的個數,setValues(PreparedStatement ps, int index)方法是實際進行插入的方法
  3)查詢單條記錄:
執行一條數據的查詢,需要使用org.springframework.jdbc.core.RowCallbackHandler接口的實現。
  4)查詢多條記錄:這裏需要用到org.springframework.jdbc.core.RowMapper接口的實現。
RowMapper接口負責把Result中的一條記錄映射成一個對象。  
 
public class StudentDaoImp implements StudentDao {
     private JdbcTemplate jdbcTemplate;
 
     @Override
     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
         this.jdbcTemplate = jdbcTemplate;
     }
     //插入單條數據
     public void insert(Student student)
     {
         String sql = "insert into student (cno,name,score) values(?,?,?)";
         //設置傳遞給通配符的參數
         Object[] params = new Object[]{student.getCno(), student.getName(), student.getScore()};
         jdbcTemplate.update(sql, params);

     }
     //批量插入數據
    public int[] batchInsert(final List<Student> list)
     {
         String sql = "insert into student (cno,name,score) values(?,?,?)";
        
         BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() {
            
             @Override
             public void setValues(PreparedStatement ps, int index) throws SQLException {
                 Student student = (Student) list.get(index);
                 ps.setInt(1, student.getCno());
                 ps.setString(2, student.getName());
                 ps.setDouble(3, student.getScore());
             }

            
             //有多少條記錄要處理
             @Override
             public int getBatchSize() {
                 return list.size();
             }

         };
        
         return jdbcTemplate.batchUpdate(sql, setter);
     }
     //查詢單條記錄
  
     public Student getStudent(final int id) {
         // 裝載查詢結果
         final Student student = new Student();
 
         String sql = "select s.cno,s.name,s.score from student s where sno = ?";
         // 設置查詢參數
         final Object[] params = new Object[] { new Integer(id) };
         // 進行查詢
         jdbcTemplate.query(sql, params, new RowCallbackHandler() {
             @Override
             public void proce***ow(ResultSet rs) throws SQLException {
                 student.setCno(rs.getInt("cno"));
                 student.setName(rs.getString("name"));
                 student.setScore(rs.getDouble("score"));
             }
         });

        
         return student;
     }

    //查詢多條記錄
   
     public List<Student> getAllStudent() {
         String sql = "select s.cno,s.name,s.score from student s";
 
         return jdbcTemplate.query(sql, new RowMapper<Student>(){
             @Override
             public Student mapRow(ResultSet rs, int index) throws SQLException {
                 Student student = new Student();
                 student.setCno(rs.getInt("cno"));
                 student.setName(rs.getString("name"));
                 student.setScore(rs.getDouble("score"));
 
                 return student;
             }
         });

     }

 }

另附:也可以使用
org.springframework.jdbc.core.RowMapper接口查詢一條記錄,只要附加查詢參數即可:
 
     public Student getStudent(final int id) {
         // 裝載查詢結果
         final Student student = new Student();
 
         String sql = "select s.cno,s.name,s.score from student s where sno = ?";
         // 設置查詢參數
         final Object[] params = new Object[] { new Integer(id) };
 
         List<Student> list = jdbcTemplate.query(sql, params,
                 new RowMapper<Student>() {
                     @Override
                     public Student mapRow(ResultSet rs, int index)
                             throws SQLException {
                         Student student = new Student();
                         student.setCno(rs.getInt("cno"));
                        student.setName(rs.getString("name"));
                        student.setScore(rs.getDouble("score"));
 
                         return student;
                     }
                 });

        
         return list.get(0);
     }


二、採用註解方式配置事務處理
   1、在
Spring配置文件beans元素中添加子元素:
  <!– 聲明事務管理器 -->   
 <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
  </bean>
 <!– 採用@Transactional註解方式使用事務  -->
  <tx:annotation-driven transaction-manager="txManager"/>

  2、在業務邏輯的試下類中使用註解添加相應的事務
   @Service @Transactional
public class StudentServiceBean implements StudentService {
@Transactional(類型=值)
public void add(Student stu) {
    dao.insert(stu);
}
}

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