[toc]
JdbcTemplate概述
JdbcTemplate是Spring框架中提供的一個對象,對原始的JDBC API進行簡單封裝,其用法與DBUtils類似.
JdbcTemplate對象的創(chuàng)建
-
配置數(shù)據(jù)源: 與
DBUtils中的QueryRunner對象類似,JdbcTemplate對象在執(zhí)行sql語句時也需要一個數(shù)據(jù)源,這個數(shù)據(jù)源可以使用C3P0或者DBCP,也可以使用Spring的內(nèi)置數(shù)據(jù)源DriverManagerDataSource.-
配置
C3P0數(shù)據(jù)源:使用
C3P0數(shù)據(jù)源,需要在bean.xml中配置如下:<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property> <property name="user" value="用戶名"></property> <property name="password" value="密碼"></property> </bean> -
配置
DBCP數(shù)據(jù)源使用
DBCP數(shù)據(jù)源,需要在bean.xml中配置如下:<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property> <property name="username" value="用戶名"></property> <property name="password" value="密碼"></property> </bean> -
使用Spring內(nèi)置的數(shù)據(jù)源
DriverManagerDataSource,需要在bean.xml中配置如下:<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property> <property name="username" value="用戶名"></property> <property name="password" value="密碼"></property> </bean>
-
-
創(chuàng)建
JdbcTemplate對象:向
JdbcTemplate中注入數(shù)據(jù)源創(chuàng)建對象,在bean.xml中配置如下:<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
JdbcTemplate的增刪改查操作
使用JdbcTemplate實現(xiàn)增刪改
與DBUtils十分類似,JdbcTemplate的增刪改操作使用其update("SQL語句", 參數(shù)...)方法
-
增加操作
public static void main(String[] args) { //1.獲取Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根據(jù)id獲取JdbcTemplate對象 JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); //3.執(zhí)行增加操作 jt.update("insert into account(name,money)values(?,?)","名字",5000); } -
刪除操作
public static void main(String[] args) { //1.獲取Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根據(jù)id獲取JdbcTemplate對象 JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); //3.執(zhí)行刪除操作 jt.update("delete from account where id = ?",6); } -
更新操作
public static void main(String[] args) { //1.獲取Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根據(jù)id獲取JdbcTemplate對象 JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); //3.執(zhí)行更新操作 jt.update("update account set money = money-? where id = ?",300,6); }
使用JdbcTemplate實現(xiàn)查詢
與DBUtils十分類似,JdbcTemplate的查詢操作使用其query()方法,其參數(shù)如下:
-
String sql: SQL語句 -
RowMapper<T> rowMapper: 指定如何將查詢結(jié)果ResultSet對象轉(zhuǎn)換為T對象 -
@Nullable Object... args: SQL語句的參數(shù)
其中RowMapper類類似于DBUtils的ResultSetHandler類,可以自己寫一個實現(xiàn)類,但常用Spring框架內(nèi)置的實現(xiàn)類BeanPropertyRowMapper<T>(T.class)
-
查詢所有:
public List<Account> findAllAccounts() { List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class)); return accounts; } -
查詢一條記錄:
public Account findAccountById(Integer accountId) { List<Account> accounts = jdbcTemplate.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), accountId); return accounts.isEmpty() ? null : accounts.get(0); } -
聚合查詢:
JdbcTemplate中執(zhí)行聚合查詢的方法為queryForObject()方法,其參數(shù)如下:String sql: SQL語句Class<T> requiredType: 返回類型的字節(jié)碼-
@Nullable Object... args: SQL語句的參數(shù)public static void main(String[] args) { //1.獲取Spring容器 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根據(jù)id獲取JdbcTemplate對象 JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate"); //3.聚合查詢 Integer total = jt.queryForObject("select count(*) from account where money > ?", Integer.class, 500); System.out.println(total); }
在DAO層使用JdbcTemplate
在DAO層直接使用JdbcTemplate
在DAO層使用JdbcTemplate,需要給DAO注入JdbcTemplate對象.
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate; // JdbcTemplate對象
// JdbcTemplate對象的set方法
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// DAO層方法
@Override
public Account findAccountById(Integer id) {
// 實現(xiàn)...
}
// DAO層方法
@Override
public Account findAccountByName(String name) {
// 實現(xiàn)...
}
// 其它DAO層方法...
}
DAO層對象繼承JdbcDaoSupport類
在實際項目中,我們會創(chuàng)建許多DAO對象,若每個DAO對象都注入一個JdbcTemplate對象,會造成代碼冗余.
- 實際的項目中我們可以讓DAO對象繼承Spring內(nèi)置的
JdbcDaoSupport類.在JdbcDaoSupport類中定義了JdbcTemplate和DataSource成員屬性,在實際編程中,只需要向其注入DataSource成員即可,DataSource的set方法中會注入JdbcTemplate對象. - DAO的實現(xiàn)類中調(diào)用父類的
getJdbcTemplate()方法獲得JdbcTemplate()對象.
JdbcDaoSupport類的源代碼如下:
public abstract class JdbcDaoSupport extends DaoSupport {
@Nullable
private JdbcTemplate jdbcTemplate; // 定義JdbcTemplate成員變量
public JdbcDaoSupport() {
}
// DataSource的set方法,注入DataSource時調(diào)用createJdbcTemplate方法注入JdbcTemplate
public final void setDataSource(DataSource dataSource) {
if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {
this.jdbcTemplate = this.createJdbcTemplate(dataSource);
this.initTemplateConfig();
}
}
// 創(chuàng)建JdbcTemplate,用來被setDataSource()調(diào)用注入JdbcTemplate
protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
// JdbcTemplate的get方法,子類通過該方法獲得JdbcTemplate對象
@Nullable
public final JdbcTemplate getJdbcTemplate() {
return this.jdbcTemplate;
}
@Nullable
public final DataSource getDataSource() {
return this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null;
}
public final void setJdbcTemplate(@Nullable JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.initTemplateConfig();
}
// ...
}
在bean.xml中,我們只要為DAO對象注入DataSource對象即可,讓JdbcDaoSupport自動調(diào)用JdbcTemplate的set方法注入JdbcTemplate
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置數(shù)據(jù)源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名"></property>
<property name="username" value="用戶名"></property>
<property name="password" value="密碼"></property>
</bean>
<!-- 配置賬戶的持久層-->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<!--不用我們手動配置JdbcTemplate成員了-->
<!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
在DAO類接口中,我們不需定義JdbcTemplate成員變量,只需定義并實現(xiàn)DAO層方法即可.
public interface IAccountDao {
// 根據(jù)id查詢賬戶信息
Account findAccountById(Integer id);
// 根據(jù)名稱查詢賬戶信息
Account findAccountByName(String name);
// 更新賬戶信息
void updateAccount(Account account);
}
在實現(xiàn)DAO接口時,我們通過super.getJdbcTemplate()方法獲得JdbcTemplate對象.
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
@Override
public Account findAccountById(Integer id) {
//調(diào)用繼承自父類的getJdbcTemplate()方法獲得JdbcTemplate對象
List<Account> list = getJdbcTemplate().query("select * from account whereid = ? ", new AccountRowMapper(), id);
return list.isEmpty() ? null : list.get(0);
}
@Override
public Account findAccountByName(String name) {
//調(diào)用繼承自父類的getJdbcTemplate()方法獲得JdbcTemplate對象
List<Account> accounts = getJdbcTemplate().query("select * from account wherename = ? ", new BeanPropertyRowMapper<Account>(Account.class), name);
if (accounts.isEmpty()) {
return null;
} else if (accounts.size() > 1) {
throw new RuntimeException("結(jié)果集不唯一,不是只有一個賬戶對象");
}
return accounts.get(0);
}
@Override
public void updateAccount(Account account) {
//調(diào)用繼承自父類的getJdbcTemplate()方法獲得JdbcTemplate對象
getJdbcTemplate().update("update account set money = ? where id = ? ", account.getMoney(), account.getId());
}
}
但是這種配置方法存在一個問題: 因為我們不能修改JdbcDaoSupport類的源代碼,DAO層的配置就只能基于xml配置,而不再可以基于注解配置了.