脚本宝典收集整理的这篇文章主要介绍了纯手写超详细讲解Spring JdbcTemplate&声明式事务,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
JdbcTemplate是sPRing框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供 了很多的操作模板类。例如F1a;操作关系型数据的JdbcTemplate和HibernateTemplate,操作noSQL数据库的 redisTemplate,操作消息队列的JmsTemplate等等。
①导入spring-jdbc和spring-tx坐标 ②创建数据库表和实体 ③创建JdbcTemplate对象 ④执行数据库操作
<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>
<!‐‐数据源相关‐‐>
<!‐‐ Druid连接池 ‐‐>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!‐‐ MySQL驱动 ‐‐>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql‐connector‐java</artifactId>
<version>5.1.39</version>
</dependency>
<!‐‐servlet相关‐‐>
<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>
创建数据库表和实体
DROP TABLE IF EXISTS account;
CREATE TABLE account (
id INT Primary KEY AUTO_INCREMENT,
NAME VArchAR(50) NOT @H_126_799@NULL,
money DOubLE NOT NULL
);
INSERT INTO account VALUES (NULL,'旺财',1000);
INSERT INTO account VALUES (NULL,'小强',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;
}
}
创建JdbcTemplate对象 执行数据库操作
//测试JdbcTemplate的开发步骤
@Test
public void test1(){
//创建数据源
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverclassname("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
//创建 模板对象
JdbcTemplate template = new JdbcTemplate();
//设置数据源
template.setDataSource(dataSource);
//执行更新操作 (添加 修改 删除)
int i = template.update("INSERT INTO account VALUES (NULL,?,?);", "如花", 1000);
System.out.println(i);
}
我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部 将数据源DataSource注入到JdbcTemplate模版对象中,然后通过Spring容器获得JdbcTemplate对象来执行操作
配置如下:
<!‐‐配置数据源 将数据的创建 交给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>
<!‐‐创建 jdbc模板对象‐‐>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<!‐‐配置数据源‐‐>
<property name="dataSource" ref="dataSource" />
</bean>
测试代码
//将spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@Contextconfiguration("classpath:applicationContext.XMl")
public class JdbcTemplateTest {
@Autowired
private JdbcTemplate jdbcTemplate;
//测试spring管理 JdbcTemplate
@Test
public void test2(){
int i = jdbcTemplate.update("INSERT INTO account VALUES (NULL,?,?);", "秋香", 1000);
System.out.println(i);
}
}
将数据库的连接信息抽取到外部配置文件中,和spring的配置文件分离开,有利于后期维护
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"/>
<!‐‐配置数据源 将数据的创建 交给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>
<!‐‐创建 jdbc模板对象‐‐>
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<!‐‐配置数据源‐‐>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
//将spring和 junit整合s
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCRUDTest {
//注入jdbc模板
@Autowired
private JdbcTemplate jdbcTemplate;
//测试修改操作
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//测试删除
@Test
public void testDelete(){
jdbcTemplate.update("DELETE from account where id = ?",1);
}
}
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;
//测试修改操作
@Test
public void testUpdate(){
jdbcTemplate.update("update account set money = ? where id = ?;",800,1);
}
//测试删除
@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);
} /
/查询一个
@Test
public void testQueryOne(){
Account account = jdbcTemplate.queryForObject("select * from account where name=?", new
BeanPropertyRowMapper<Account>(Account.class), "旺财");
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);
}
}
①导入spring-jdbc和spring-tx坐标 ②创建数据库表和实体 ③创建JdbcTemplate对象
JdbcTemplate jdbcTemplate = newJdbcTemplate();
jdbcTemplate.setDataSource(dataSource);
④执行数据库操作
更新操作:
jdbcTemplate.update (sql,params)
查询操作:
jdbcTemplate.query (sql,Mapper,params)
jdbcTemplate.queryForObject(sql,Mapper,params)
@H_406_2609@概念:
事务是一组操作的执行单元,相对于数据库操作来讲,事务管理的是一组SQL指令,比如增加,修改,删除等,事 务的一致性,要求,这个事务内的操 作必须全部执行成功,如果在此过程种出现了差错,比如有一条SQL语句没有执行成功,那么这一组操作都将全部 回滚。 仅用四个词解释事务(ACID) 1.atomic(原子性):要么都发生,要么都不发生。 2.consistent(一致性):数据应该不被破坏。 3.Isolate(隔离性):用户间操作不相混淆 4.Durable(持久性):永久保存,例如保存到数据库中等
Spring 的声明式事务顾名思义就是采用声明的方式来处理事务。这里所说的声明,就是指在配置文件中声明,用在Spring 配置文件中声明式的处理事务来代替代码式的处理事务
声明式事务处理的作用
注意:Spring 声明式事务控制底层就是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">
编写 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.编写 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);
}
}
<!‐‐之前省略datsSource、jdbcTemplate‐‐>
<!‐‐平台事务管理器‐‐>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!‐‐事务的注解驱动‐‐>
<tx:annotation‐driven/>
① 使用 @Transactional 在需要进行事务控制的类或是方法上修饰,注解可用的属性同 xml 配置方式,例如隔离级别、传播行为等。 ②注解使用在类上,那么该类下的所有方法都使用同一套注解参数配置。 ③使用在方法上,不同的方法可以采用不同的事务参数配置。 ④ Xml 配置文件中要开启事务的注解驱动 <tx:annotation-driven />
注解声明式事务控制的配置要点
事务通知的配置 (@Transactional
注解配置 )
事务注解驱动的配置 <tx:annotation-driven/>
以上是脚本宝典为你收集整理的纯手写超详细讲解Spring JdbcTemplate&声明式事务全部内容,希望文章能够帮你解决纯手写超详细讲解Spring JdbcTemplate&声明式事务所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。