純手寫(xiě)超詳細(xì)講解Spring JdbcTemplate&聲明式事務(wù)

JdbcTemplate基本使用
1-JdbcTemplate基本使用-概述(了解)
JdbcTemplate是spring框架中提供的一個(gè)對(duì)象,是對(duì)原始繁瑣的Jdbc API對(duì)象的簡(jiǎn)單封裝。spring框架為我們提供了很多的操作模板類。例如:操作關(guān)系型數(shù)據(jù)的JdbcTemplate和HibernateTemplate,操作nosql數(shù)據(jù)庫(kù)的RedisTemplate,操作消息隊(duì)列的JmsTemplate等等。
2-JdbcTemplate基本使用-開(kāi)發(fā)步驟(理解)
①導(dǎo)入spring-jdbc和spring-tx坐標(biāo)
②創(chuàng)建數(shù)據(jù)庫(kù)表和實(shí)體
③創(chuàng)建JdbcTemplate對(duì)象
④執(zhí)行數(shù)據(jù)庫(kù)操作
3-JdbcTemplate基本使用-快速入門代碼實(shí)現(xiàn)(應(yīng)用)
導(dǎo)入spring-jdbc和spring-tx坐標(biāo)
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐context</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐test</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐jdbc</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring‐tx</artifactId>
<version>5.2.8.RELEASE</version>
</dependency>
<!‐‐織入包‐‐>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<!‐‐數(shù)據(jù)源相關(guān)‐‐>
<!‐‐ Druid連接池 ‐‐>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!‐‐ mysql驅(qū)動(dòng) ‐‐>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql‐connector‐java</artifactId>
<version>5.1.39</version>
</dependency>
<!‐‐servlet相關(guān)‐‐>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet‐api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp‐api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>創(chuàng)建數(shù)據(jù)庫(kù)表和實(shí)體
DROP TABLE IF EXISTS account;
CREATE TABLE account (
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(50) NOT NULL,
money DOUBLE NOT NULL
);
INSERT INTO account VALUES (NULL,'旺財(cái)',1000);
INSERT INTO account VALUES (NULL,'小強(qiáng)',1000);
SELECT * FROM account;package com.summer.domain;
public class Account {
private int id;
private String name;
private double money;
public int getId() {
return id;
}
public void setId(int 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;
}
}創(chuàng)建JdbcTemplate對(duì)象
執(zhí)行數(shù)據(jù)庫(kù)操作
//測(cè)試JdbcTemplate的開(kāi)發(fā)步驟
@Test
public void test1(){
//創(chuàng)建數(shù)據(jù)源
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
//創(chuàng)建 模板對(duì)象
JdbcTemplate template = new JdbcTemplate();
//設(shè)置數(shù)據(jù)源
template.setDataSource(dataSource);
//執(zhí)行更新操作 (添加 修改 刪除)
int i = template.update("INSERT INTO account VALUES (NULL,?,?);", "如花", 1000);
System.out.println(i);
}4-JdbcTemplate基本使用-spring產(chǎn)生模板對(duì)象分析(理解)
我們可以將JdbcTemplate的創(chuàng)建權(quán)交給Spring,將數(shù)據(jù)源DataSource的創(chuàng)建權(quán)也交給Spring,在Spring容器內(nèi)部將數(shù)據(jù)源DataSource注入到JdbcTemplate模版對(duì)象中,然后通過(guò)Spring容器獲得JdbcTemplate對(duì)象來(lái)執(zhí)行操作
5-JdbcTemplate基本使用-spring產(chǎn)生模板對(duì)象代碼實(shí)現(xiàn)(應(yīng)用)
配置如下:
<!‐‐配置數(shù)據(jù)源 將數(shù)據(jù)的創(chuàng)建 交給spring容器‐‐>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!‐‐創(chuàng)建 jdbc模板對(duì)象‐‐>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<!‐‐配置數(shù)據(jù)源‐‐>
<property name="dataSource" ref="dataSource" />
</bean>測(cè)試代碼
//將spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
//測(cè)試spring管理 JdbcTemplate
@Test
public void test2(){
int i = jdbcTemplate.update("INSERT INTO account VALUES (NULL,?,?);", "秋香", 1000);
System.out.println(i);
}
}6-JdbcTemplate基本使用-spring產(chǎn)生模板對(duì)象代碼實(shí)現(xiàn)
將數(shù)據(jù)庫(kù)的連接信息抽取到外部配置文件中,和spring的配置文件分離開(kāi),有利于后期維護(hù)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root配置文件修改為:
<?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
">
<!‐‐加載properties配置文件‐‐>
<context:property‐placeholder location="classpath:jdbc.properties"/>
<!‐‐配置數(shù)據(jù)源 將數(shù)據(jù)的創(chuàng)建 交給spring容器‐‐>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!‐‐創(chuàng)建 jdbc模板對(duì)象‐‐>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<!‐‐配置數(shù)據(jù)源‐‐>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>7-JdbcTemplate基本使用-常用操作-更新操作(應(yīng)用)
//將spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//注入jdbc模板
@Autowired
private JdbcTemplate jdbcTemplate;
//測(cè)試修改操作
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//測(cè)試刪除
@Test
public void testDelete(){
jdbcTemplate.update("DELETE from account where id = ?",1);
}
}8-JdbcTemplate基本使用-常用操作-查詢操作(應(yīng)用)
package com.summer.test;
import com.summer.domain.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
//將spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//注入jdbc模板
@Autowired
private JdbcTemplate jdbcTemplate;
//測(cè)試修改操作
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//測(cè)試刪除
@Test
public void testDelete(){
jdbcTemplate.update("DELETE from account where id = ?",1);
} /
/聚合查詢
@Test
public void testQueryCount(){
Long count = jdbcTemplate.queryForObject("select count(*) from account", Long.class);
System.out.println(count);
} /
/查詢一個(gè)
@Test
public void testQueryOne(){
Account account = jdbcTemplate.queryForObject("select * from account where name=?", new
BeanPropertyRowMapper<Account>(Account.class), "旺財(cái)");
System.out.println(account);
} /
/查詢所有
@Test
public void testQueryAll(){
List<Account> accountList = jdbcTemplate.query("select * from account", new
BeanPropertyRowMapper<Account>(Account.class));
System.out.println(accountList);
}
}9-JdbcTemplate基本使用-知識(shí)要點(diǎn)(理解,記憶)
①導(dǎo)入spring-jdbc和spring-tx坐標(biāo)
②創(chuàng)建數(shù)據(jù)庫(kù)表和實(shí)體
③創(chuàng)建JdbcTemplate對(duì)象
JdbcTemplate jdbcTemplate = newJdbcTemplate();
jdbcTemplate.setDataSource(dataSource);④執(zhí)行數(shù)據(jù)庫(kù)操作
更新操作:
jdbcTemplate.update (sql,params)查詢操作:
jdbcTemplate.query (sql,Mapper,params)jdbcTemplate.queryForObject(sql,Mapper,params)聲明式事務(wù)控制
1.事務(wù)的概念
概念:
事務(wù)是一組操作的執(zhí)行單元,相對(duì)于數(shù)據(jù)庫(kù)操作來(lái)講,事務(wù)管理的是一組SQL指令,比如增加,修改,刪除等,事務(wù)的一致性,要求,這個(gè)事務(wù)內(nèi)的操作必須全部執(zhí)行成功,如果在此過(guò)程種出現(xiàn)了差錯(cuò),比如有一條SQL語(yǔ)句沒(méi)有執(zhí)行成功,那么這一組操作都將全部回滾。
僅用四個(gè)詞解釋事務(wù)(ACID)
1.atomic(原子性):要么都發(fā)生,要么都不發(fā)生。
2.consistent(一致性):數(shù)據(jù)應(yīng)該不被破壞。
3.Isolate(隔離性):用戶間操作不相混淆
4.Durable(持久性):永久保存,例如保存到數(shù)據(jù)庫(kù)中等
2 .基于注解的聲明式事務(wù)控制
2.1 什么是聲明式事務(wù)控制
Spring 的聲明式事務(wù)顧名思義就是采用聲明的方式來(lái)處理事務(wù)。這里所說(shuō)的聲明,就是指在配置文件中聲明,用在Spring 配置文件中聲明式的處理事務(wù)來(lái)代替代碼式的處理事務(wù)
聲明式事務(wù)處理的作用
事務(wù)管理不侵入開(kāi)發(fā)的組件。具體來(lái)說(shuō),業(yè)務(wù)邏輯對(duì)象就不會(huì)意識(shí)到正在事務(wù)管理之中,事實(shí)上也應(yīng)該如此,因?yàn)槭聞?wù)管理是屬于系統(tǒng)層面的服務(wù),而不是業(yè)務(wù)邏輯的一部分,如果想要改變事務(wù)管理策劃的話,也只需要在定義文件中重新配置即可在不需要事務(wù)管理的時(shí)候,只要在設(shè)定文件上修改一下,即可移去事務(wù)管理服務(wù),無(wú)需改變代碼重新編譯,這樣維護(hù)起來(lái)極其方便
注意:Spring 聲明式事務(wù)控制底層就是AOP。
引入aop、tx命名空間
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring‐context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring‐aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring‐tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring‐beans.xsd">2.2 使用注解配置聲明式事務(wù)控制
1.編寫(xiě) AccoutDao
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void out(String outMan, double money) {
jdbcTemplate.update("update account set money=money‐? where name=?",money,outMan);
}
public void in(String inMan, double money) {
jdbcTemplate.update("update account set money=money+? where name=?",money,inMan);
}
}2.編寫(xiě) AccoutService
@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
public void transfer(String outMan, String inMan, double money) {
accountDao.out(outMan,money);
int i = 1/0;
accountDao.in(inMan,money);
}
}3.編寫(xiě) applicationContext.xml 配置文件
<!‐‐之前省略datsSource、jdbcTemplate‐‐>
<!‐‐平臺(tái)事務(wù)管理器‐‐>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!‐‐事務(wù)的注解驅(qū)動(dòng)‐‐>
<tx:annotation‐driven/>2.3 注解配置聲明式事務(wù)控制解析
① 使用 @Transactional 在需要進(jìn)行事務(wù)控制的類或是方法上修飾,注解可用的屬性同 xml 配置方式,例如隔離級(jí)別、傳播行為等。
②注解使用在類上,那么該類下的所有方法都使用同一套注解參數(shù)配置。
③使用在方法上,不同的方法可以采用不同的事務(wù)參數(shù)配置。
④ Xml 配置文件中要開(kāi)啟事務(wù)的注解驅(qū)動(dòng) <tx:annotation-driven />
2.4 知識(shí)要點(diǎn)
注解聲明式事務(wù)控制的配置要點(diǎn)
事務(wù)通知的配置 (@Transactional注解配置 )
事務(wù)注解驅(qū)動(dòng)的配置 <tx:annotation-driven/>
出處:blog.csdn.net/xt623/article/details/120396471
關(guān)注GitHub今日熱榜,專注挖掘好用的開(kāi)發(fā)工具,致力于分享優(yōu)質(zhì)高效的工具、資源、插件等,助力開(kāi)發(fā)者成長(zhǎng)!
點(diǎn)個(gè)在看,你最好看
