Spring 使用dataSource、JdbcTemplate簡化數據庫操作
我們在java代碼中使用jdbc中,總是會有很多重複的代碼區,可能真正操作數據庫的代碼只佔了20%。作爲一名程序員應該簡化這些需要重複的部分很着重於核心的數據庫操作部分。
Spring提供的jdbcTemplate很好的幫我們解決了問題,讓我們真正的只用關心編寫操作數據庫的代碼。
在spring中使用數據源是很好的方案,第一步我們來配置一個c3p0數據源在spring 的配置中:
<!--從類路徑下導入jdbc.properties 文件 配置信息放置於其中-->
<util:properties id="jdbc" location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="jdbcUrl" value="#{jdbc.url}" />
<property name="driverClass" value="#{jdbc.driverClassName}" />
<property name="user" value="#{jdbc.username}" />
<property name="password" value="#{jdbc.password}" />
<!--連接池中保留的最大連接數。Default: 15 -->
<property name="maxPoolSize" value="100" />
<!--連接池中保留的最小連接數。-->
<property name="minPoolSize" value="1" />
<!--初始化時獲取的連接數,取值應在minPoolSize與maxPoolSize之間。Default: 3 -->
<property name="initialPoolSize" value="10" />
<!--最大空閒時間,60秒內未使用則連接被丟棄。若爲0則永不丟棄。Default: 0 -->
<property name="maxIdleTime" value="30" />
<!--當連接池中的連接耗盡的時候c3p0一次同時獲取的連接數。Default: 3 -->
<property name="acquireIncrement" value="5" />
<!--JDBC的標準參數,用以控制數據源內加載的PreparedStatements數量。但由於預緩存的statements
屬於單個connection而不是整個連接池。所以設置這個參數需要考慮到多方面的因素。
如果maxStatements與maxStatementsPerConnection均爲0,則緩存被關閉。Default: 0-->
<property name="maxStatements" value="0" />
<!--每60秒檢查所有連接池中的空閒連接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!--定義在從數據庫獲取新連接失敗後重復嘗試的次數。Default: 30 -->
<property name="acquireRetryAttempts" value="30" />
<!--獲取連接失敗將會引起所有等待連接池來獲取連接的線程拋出異常。但是數據源仍有效
保留,並在下次調用getConnection()的時候繼續嘗試獲取連接。如果設爲true,那麼在嘗試
獲取連接失敗後該數據源將申明已斷開並永久關閉。Default: false-->
<property name="breakAfterAcquireFailure" value="true" />
<!--因性能消耗大請只在需要的時候使用它。如果設爲true那麼在每個connection提交的
時候都將校驗其有效性。建議使用idleConnectionTestPeriod或automaticTestTable
等方法來提升連接測試的性能。Default: false -->
<property name="testConnectionOnCheckout" value="false" />
</bean>
我們使用了Spring 提供的<util:properties/>將jdbc配置文件導入爲一個bean 並使用#{...}的方式導入
Jdbc.properties文件提供jdbc連接信息:
url=jdbc:mysql:///testdb
driverClassName=com.mysql.jdbc.Driver
username=root
password=20080808
接下來就是最重要的一步了,配置好jdbc模板(jdbcTemplate)
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
將數據源以構造注入的方式注入
這樣我們就可以在代碼中通過getBean的方式獲取了。
JdbcTemplate template = beanContext.getBean("jdbcTemplate", JdbcTemplate.class);
Persion persion = (Persion) template.queryForObject("select * from t_persion where name=?", new Object[]{"zhao"},
new RowMapper<Persion>() {
@Override
public Persion mapRow(ResultSet rs, int rowNum) throws SQLException {
Persion p = new Persion();
p.setName(rs.getString("name"));
p.setAge(rs.getInt("age"));
p.setId(rs.getInt("id"));
return p;
}
});
System.out.println(persion);
對於jdbcTemplate的操作api 官方文檔又詳細的解釋
jdbcTemplate是線程安全的
我們可以直接將Dao作爲一個bean 將jdbcTemplate注入其中
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<bean id="persionDao" class="cn.zhaoyuening.dao.PersionDao">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
persionDao代碼:
public class PersionDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void addPersion(Persion persion){...}
public void removePersionById(int id){...}
public Persion getPersionByName(String name) {
Persion persion = (Persion) jdbcTemplate.queryForObject("select * from t_persion where name=?", new Object[]{"zhao"},
new RowMapper<Persion>() {
@Override
public Persion mapRow(ResultSet rs, int rowNum) throws SQLException {
Persion p = new Persion();
p.setName(rs.getString(name));
p.setAge(rs.getInt("age"));
p.setId(rs.getInt("id"));
return p;
}
});
return persion;
}
}