日期:2014-05-16  浏览次数:20445 次

【转】spring数据源的注入.JDBC模版管理

对于不同的数据库连接来源需求,spring提供了javax.sql.DataSource注入,更换数据来源只要在Bean定义中修改配置,而不用修改任何一行代码。
         应不同的系统,可能使用不同的数据来源,例如:jdbc、连接池、或是JNDI等等,资料变更是底层的行为,不应影响到上层的业务逻辑。
例子:
<beans>
       <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource">
           <property name="driverClassName">
               <value>com.mysql.jdbc.Driver</value>
           </property>
           <property name="url">
               <value>jdbc:mysql://localhost:3306/demo</value>
           </property>
           <property name="username">
               <value>caterpillar</value>
           </property>
           <property name="password">
               <value>123456</value>
           </property>
       </bean>
         <bean id="userDao" class="onlyfun.caterpillar.UserDao">
            <property name="dataSource">
               <ref bean="datasource"/>
            </property>
      </bean>
</beans>
其中"driverClassName"、"url"、"username"、"password"四個屬性分別用來設定JDBC驅動程式類別、資料庫 URL協定、使用者名稱、密碼,而DriverManagerDataSource继承了javax.sql.DataSource.
注意:
(1)、该例子使用的是简单的jdbc连接,如果应用到工程,必须使用连接池,这时只要更换class属性为class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
(2)、如果采用的是JNDI连接,可以这么设定:
<bean id="dataSource"
      class="org.springframework.indi.JndiObjectFactoryBean">
      <property name="jndiName">
         <value>jdbc/demo</value>
        </property>
</bean>
Spring学习笔记JDBC模版管理
对于Spring应用,Spring 提供了一个更好的数据持久化的框架,Spring让持久层的类UserDao继承 org.springframework.jdbc.core.JdbcTemplate这个封装了jdbc操作的类,要建立JdbcTemplate的实例,必须要有一个DataSource物件作为建构时的物件.
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
例子(1):-----取得模版
package onlyfun.caterpillar;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDAO implements IUserDAO {
      private JdbcTemplate jdbcTemplate;
      public void setDataSource(DataSource dataSource) {
          jdbcTemplate = new JdbcTemplate(dataSource);
      }
          return null;
      }
}
例子(2):-----update操作(同样的操作适用于update、insert、delete)
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate
.update(
"