Day57(spring註解高階 事務)57
阿新 • • 發佈:2021-08-10
一、Spring中對的Jdbc封裝
1、JdbcTemplate
1.1、概述
1.1.1、基本介紹
Spring對資料庫的操作在jdbc上面做了基本的封裝,讓開發者在操作資料庫時只需關注SQL語句和查詢 結果處理器,即可完成功能(當然,只使用JdbcTemplate,還不能擺脫持久層實現類的編寫)。
在配合spring的IoC功能,可以把DataSource註冊到JdbcTemplate之中。同時利用spring基於 aop的事務即可完成簡單的資料庫CRUD操作。
JdbcTemplate的限定命名為org.springframework.jdbc.core.JdbcTemplate。要使用 JdbcTemlate需要匯入spring-jdbc和spring-tx兩個座標。
1.1.2、原始碼
/**
* JdbcTemplate實現了JdbcOperations介面,操作方法都定義在此介面中
*/
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
/**
* 使用預設建構函式構建JdbcTemplate
*/
public JdbcTemplate() {
}
/**
* 通過資料來源構建JdbcTemplate
*/
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
/**
* 當使用預設建構函式構建時,提供了設定資料來源的方法
*/
public void setDataSource(
1.1.3、方法說明
execute方法: 可以用於執行任何SQL語句,一般用於執行DDL語句;
update方法及batchUpdate方法: update方法用於執行新增、修改、刪除等語句;batchUpdate方法用於執行批處理相關語 句;
query方法及queryForXXX方法: 用於執行查詢相關語句;
call方法: 用於執行儲存過程、函式相關語句。
1.2、入門案例
1.2.1、匯入座標
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
1.2.2、編寫實體類
/**
* @author 黑馬程式設計師
* @Company http://www.itheima.com
*/
public class Account implements Serializable{
private Integer id;
private String name;
private Double money;
public Integer getId() {
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
1.2.3、編寫配置類
/**
* @author 黑馬程式設計師
* @Company http://www.itheima.com
*/
/**
* @author 黑馬程式設計師
* @Company http://www.itheima.com
*/
public class JdbcConfig {
1.2.4、編寫配置檔案
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_ioc
jdbc.username=root
jdbc.password=1234
1.2.5、測試方法
/**
* @author 黑馬程式設計師
* @Company http://www.itheima.com
*/