Spring的 JDBCTemplate和宣告式事務控制
阿新 • • 發佈:2020-07-26
Spring 中的 JdbcTemplate[會用]
JdbcTemplate 概述
它是 spring 框架中提供的一個物件,是對原始 Jdbc API 物件的簡單封裝。spring 框架為我們提供了很多 的操作模板類。 操作關係型資料的: JdbcTemplate HibernateTemplate 操作 nosql 資料庫的: RedisTemplate 操作訊息佇列的: JmsTemplate 我們今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我們在導包的時候,除了要匯入這個 jar 包 外,還需要匯入一個 spring-tx-5.0.2.RELEASE.jar(它是和事務相關的)。
物件的建立
我們可以參考它的原始碼,來一探究竟: public JdbcTemplate() { } public JdbcTemplate(DataSource dataSource) { setDataSource(dataSource); afterPropertiesSet(); } public JdbcTemplate(DataSource dataSource, boolean lazyInit) { setDataSource(dataSource); setLazyInit(lazyInit); afterPropertiesSet(); } 除了預設建構函式之外,都需要提供一個數據源。既然有set方法,依據我們之前學過的依賴注入,我們可以 在配置檔案中配置這些物件。
spring 中配置資料來源
bean.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.itheim"/> <bean id="accountDao" class="com.itheim.dao.Imp.accountDaoImp"> <property name="dataSource" ref="dataSource"/> </bean> <!--配置Jdbc--> <bean id="jdbc" class="org.springframework.jdbc.core.JdbcTemplate" > <constructor-arg name="dataSource" ref="dataSource"/> </bean> <!--配置資料來源 配置 Jdbc資料來源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/eesy"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> </beans>
配置 DBCP 資料來源
匯入 到工程的 lib 目錄。在 spring 的配置檔案中配置:
<!-- 配置資料來源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:// /spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
配置C3p0資料來源
匯入 到工程的 lib 目錄。在 spring 的配置檔案中配置:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
將資料庫連線的資訊配置到屬性檔案中:
【定義屬性檔案】
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_day02
jdbc.username=root
jdbc.password=123
【引入外部的屬性檔案】
一種方式:
<!-- 引入外部屬性檔案: -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties"/>
</bean>
另一種方式:
<context:property-placeholder location="classpath:jdbc.properties"/>
基本使用
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據 id 獲取 bean 物件
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.執行操作
jt.execute("insert into account(name,money)values('eee',500)");
}
}
** 儲存操作**
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據 id 獲取 bean 物件
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.執行操作
//儲存
jt.update("insert into account(name,money)values(?,?)","fff",5000);
}
}
查詢一個
使用 RowMapper 的方式:常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據 id 獲取 bean 物件
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.執行操作
//查詢一個
List<Account> as = jt.query("select * from account where id = ? ",
new AccountRowMapper(), 55);
System.out.println(as.isEmpty()?"沒有結果":as.get(0));
}
}
用 使用 ResultSetExtractor 的方式: 不常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.獲取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據 id 獲取 bean 物件
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.執行操作
//查詢一個
Account account = jt.query("select * from account where id = ?",
new AccountResultSetExtractor(),3);
System.out.println(account);
}
}
讓 dao 繼承 JdbcDaoSupport
JdbcDaoSupport 是spring 框架為我們提供的一個類,該類中定義了一個 JdbcTemplate 物件,我們可以
直接獲取使用,但是要想建立該物件,需要為其提供一個數據源:
public class accountDaoImp extends JdbcDaoSupport implements accountDao {
@Override
public List<Account> saveUser() {
// jt=new JdbcTemplate(dataSource);
List<Account> list = super.getJdbcTemplate().query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
if (list != null) {
return list;
} else {
return null;
}
}
}
思考:
版 兩版 Dao 有什麼區別呢?
答案:
在 第一種在 Dao 類中定義 JdbcTemplate 的方式,適用於所有配置方式(xml 和註解都可以)。
讓 第二種讓 Dao 繼承 JdbcDaoSupport 的方式,只能用於基於 XML