Spring JDBC 框架由四大模組組成,JdbcTemplate 作為 Core 包的核心類,極大簡化了 JDBC 開發。本文系統梳理框架架構、數據源配置方案及核心 API 使用。
| 模組 | 包路徑 | 核心職責 |
|---|---|---|
| Core | org.springframework.jdbc.core | JdbcTemplate、RowMapper、ResultSetExtractor 等核心模板類 |
| DataSource | org.springframework.jdbc.datasource | 數據源工具類、簡單實現類、事務管理集成 |
| Object | org.springframework.jdbc.object | RDBMS 操作對象化:MappingSqlQuery、SqlUpdate、SqlCall |
| Support | org.springframework.jdbc.support | 異常轉換(SQLException → DataAccessException)、工具類 |
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
需引入 c3p0-0.9.5.x.jar
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
需引入 commons-dbcp.jar 和 commons-pool.jar
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
在 DAO 中注入:
<bean id="userDao" class="com.example.UserDAOImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
String result = (String) getJdbcTemplate().execute(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) throws SQLException {
CallableStatement cs = con.prepareCall("{call proc_name(?,?)}");
cs.setString(1, "inputParam");
cs.registerOutParameter(2, Types.VARCHAR);
return cs;
}
},
new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement cs) throws SQLException, DataAccessException {
cs.execute();
return cs.getString(2);
}
}
);
// 單條
jdbcTemplate.update("insert into t_user(name,age) values(?,?)", "Tom", 25);
// 批量
String sql = "insert into t_user(name,age) values(?,?)";
List<Object[]> batchArgs = Arrays.asList(new Object[][]{{"A",1},{"B",2}});
jdbcTemplate.batchUpdate(sql, batchArgs);
// 單值
Integer count = jdbcTemplate.queryForObject("select count(*) from t_user", Integer.class);
// 單對象
User user = jdbcTemplate.queryForObject("select * from t_user where id=?", new BeanPropertyRowMapper<>(User.class), 1);
// 列表
List<User> list = jdbcTemplate.query("select * from t_user", new BeanPropertyRowMapper<>(User.class));
BeanPropertyRowMapper 減少手寫映射代碼batchUpdate 顯著提升性能理解框架架構與配置本質,才能在實際項目中靈活應對各種數據訪問場景。