一、spring对JDBC的支持

JdbcTemplate 简介

为了使 JDBC 更加易于使用, Spring 在 JDBC API 上定义了一个抽象层, 以此建立一个 JDBC 存取框架. 作为 Spring JDBC 框架的核心, JDBC 模板的设计目的是为不同类型的 JDBC 操作提供模板方法. 每个模板方法都能控制整个过程, 并允许覆盖过程中的特定任务. 通过这种方式, 可以在尽可能保留灵活性的情况下, 将数据库存取的工作量降到最低.

步骤:

1.在工程中加入相应的jar包

2.在spring的配置文件中配置数据源bean和配置JDBCTemplate的bean

<?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.zhiyou100.xz"></context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源:数据库交互的。c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
</bean>
<!-- 配置springjdbc的模板类 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean> </beans>

3.spring配置文件中引入的属性文件

#数据源的信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root

二、spring中的事务管理

spring中的事务管理简单介绍

作为企业级应用程序框架, Spring 在不同的事务管理 API 之上定义了一个抽象层. 而应用程序开发人员不必了解底层的事务管理 API, 就可以使用 Spring 的事务管理机制.

Spring 既支持编程式事务管理, 也支持声明式的事务管理.

编程式事务管理: 将事务管理代码嵌入到业务方法中来控制事务的提交和回滚. 在编程式管理事务时, 必须在每个事务操作中包含额外的事务管理代码.

声明式事务管理: 大多数情况下比编程式事务管理更好用. 它将事务管理代码从业务方法中分离出来, 以声明的方式来实现事务管理. 事务管理作为一种横切关注点, 可以通过 AOP 方法模块化. Spring 通过 Spring AOP 框架支持声明式事务管理.

spring中的事务管理器

Spring 从不同的事务管理 API 中抽象了一整套的事务机制. 开发人员不必了解底层的事务 API, 就可以利用这些事务机制. 有了这些事务机制, 事务管理代码就能独立于特定的事务技术了.

Spring 的核心事务管理抽象是interface Platform TransactionManager, 它为事务管理封装了一组独立于技术的方法. 无论使用 Spring 的哪种事务管理策略(编程式或声明式), 事务管理器都是必须的.

1.用@Transactional 注解声明式的管理事务

添加事务与切面相关的jar包

用于在配置文件中引入的属性文件db.properties

#数据源的信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
#不能使用user.name或username
jdbc.username=root
jdbc.password=root

配置spring的配置文件

<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <!-- 包扫描 -->
<context:component-scan base-package="com.zhiyou100.xz"></context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源:数据库交互的。c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
</bean>
<!-- 配置springjdbc的模板类 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 定义一个事物管理类 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean> <!-- 开始注解 :如果你的事务管理bean的id叫transactionManager 那么transaction-manager可以省略-->
<tx:annotation-driven transaction-manager="transactionManager"/> </beans>

示例:以订购图书为例

建立接口BookShopDao

public interface BookShopDao {
public void updateStock(String isbn);
public double findByBookIsbn(String isbn);
public void updateAccount(String username,double money);
}

建立接口BookShopDao的实现类

@Repository
public class BookShopDaoImp implements BookShopDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void updateStock(String isbn) {
//当库存不足时
//查询库存
String sql1="select stock from book_stock where isbn=?";
Integer stock=jdbcTemplate.queryForObject(sql1,Integer.class ,isbn);
if(stock<=0) {
throw new RuntimeException("书的库存不足");
}
String sql="update book_stock set stock=stock-1 where isbn=?";
jdbcTemplate.update(sql,isbn); } @Override
public double findByBookIsbn(String isbn) {
String sql="select price from book where isbn=?";
return jdbcTemplate.queryForObject(sql, Double.class, isbn);
} @Override
public void updateAccount(String username, double money) {
//当余额不足时
String sql1="select balance from account where username=?";
double balance=jdbcTemplate.queryForObject(sql1,Double.class ,username);
if(balance<money) {
throw new RuntimeException("账户余额不足");
}
String sql="update account set balance=balance-? where username=?";
jdbcTemplate.update(sql, money,username); } }

建立接口BookShopService:购买业务

public interface BookShopService {

    public void purchase(String username,String isbn);
}

建立接口BookShopService的实现类

@Service
//事物注解
public class BookShopServiceImp implements BookShopService { @Autowired
private BookShopDao bookShopDao; //订购 事物管理
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void purchase(String username, String isbn) {
//1.查询该书的价格
double price=bookShopDao.findByBookIsbn(isbn);
//2.修改书的库存
bookShopDao.updateStock(isbn);
//3.修改用户余额
bookShopDao.updateAccount(username, price);
} }

建立接口Cashier:结账功能

public interface Cashier {

    public void checkOut(String username,List<String> isbns);
}

建立接口Cashier的实现类

@Component
public class BookShopCashier implements Cashier { @Autowired
private BookShopService bookShopService; public void checkOut(String username, List<String> isbns) {
for(String isbn:isbns ) {
bookShopService.purchase(username,isbn);
}
} }

测试

public class Test {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("app2.xml");
// BookShopService bookShopService=(BookShopService) app.getBean("bookShopServiceImp");
// bookShopService.purchase("TOM", "0001");
//当余额只能支付第一本书,不够支付第二本,就买第一本书
Cashier c=(Cashier) app.getBean("bookShopCashier");
List<String> list=new ArrayList<String>();
list.add("0001");
list.add("0002");
c.checkOut("TOM", list);
}
}

2.用xml方式完成声明式的管理事务

配置spring的配置文件

<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"> <!-- 包扫描 -->
<context:component-scan base-package="com.zhiyou100.xz.service.xml,com.zhiyou100.xz.dao"></context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源:数据库交互的。c3p0 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
</bean>
<!-- 配置springjdbc的模板类 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean> <!-- 定义一个事物管理类 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean> <!--建议:设置方法属性 -->
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<!-- read-only设置只读 用于查询 -->
<tx:method name="query*" read-only="true"/>
          <!-- propagation="REQUIRED" 可省略不写,因为为默认 -->
<tx:method name="purchase*" propagation="REQUIRED"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice> <!-- 切面的设置 -->
<aop:config>
<!-- 切点 业务层所在的包 -->
<aop:pointcut expression="execution(* com.zhiyou100.xz.service.xml.*.*(..))" id="pointcut"/>
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
</aop:config> </beans>

去掉以上示例中BookShopServiceImp中的@Transactional(propagation=Propagation.REQUIRES_NEW)

测试

public class Test2 {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("app3.xml");
BookShopService bookShopService=(BookShopService) app.getBean("bookShopServiceImp");
bookShopService.purchase("TOM", "0001"); }
}

spring学习日志四的更多相关文章

  1. spring 学习(四): spring 的 jdbcTemplate 操作

    spring 学习(四): spring 的 jdbcTemplate 操作 spring 针对 javaee 的每一层,都提供了相应的解决技术,jdbcTemplate 的主要操作在 dao 层. ...

  2. Spring学习笔记四:SpringAOP的使用

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6776247.html  一:AOP基础概念 (1)通知(增强)Advice 通知,其实就是我们从众多类中提取出 ...

  3. spring学习日志三

    一.回顾 1.1 依赖注入的方式. set方法来注入 <property name="属性名" /> 构造方法来注入<construtor-arg index=& ...

  4. 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】

    一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...

  5. Spring学习(四)——使用Spring JDBC访问数据库

    本篇我们将在上一篇http://www.cnblogs.com/wenjingu/p/3824294.html的Demo程序的基础上增加数据持久层和业务层,实现登录验证功能. 1.修改gradle文件 ...

  6. Spring 学习十四 Spring security安全

    Spring security: 我用过的安全机制:   oauth2, filter,  secured方法保护 9.2  保护web请求: 9.2.1  代理Servlet过滤器: Delegat ...

  7. <黑马新秀>Spring学习日志

    # 用于梳理Spring知识点 Spring是分层的Java EE应用全栈轻量级开源框架,以IoC(Inverse Of Control反转控制)和AOP(Aspect Oriented Progra ...

  8. spring学习笔记四:AOP

    AOP(Aspect Orient Programming),面向切面编程,是对面向对象编程OOP的一种补充 面向对象编程使用静态角度考虑程序的结构,而面向切面编程是从动态角度考虑程序运行过程 AOP ...

  9. Spring学习(四)IOC详解

    一.简介 概念:控制反转是一种通过描述(在 Java 中可以是 XML 或者注解)并通过第三方(Spring)去产生或获取特定对象的方式.(被动创建) 优势: ① 降低对象之间的耦合 ② 我们不需要理 ...

随机推荐

  1. Docker搭建Redis5.0并挂载数据

    记录 Docker 搭建 Redis5.0 并挂载数据过程,搭建参考自 Docker Hub 系列文章欢迎访问:https://www.itwxe.com/posts/9e76db89/ 一.简单挂载 ...

  2. ZYNQ FLASH+EMMC手动移植LINUX启动

    前言 虽可使用Petalinux进行移植,简单方便,但为了更清楚明白的了解整个流程,还是尝试了一波手动移植. 参考资料 ZYNQ Linux 移植:包含petalinux移植和手动移植debian9 ...

  3. java 8新特性 并行流

    使用并行流,提高cpu利用率,提高运算速度 /** * java 8并行流 * 底层运用fork join框架 */ @Test public void test(){ Instant start = ...

  4. 浅谈树模型与集成学习-从决策树到GBDT

    引言   神经网络模型,特别是深度神经网络模型,自AlexNet在Imagenet Challenge 2012上的一鸣惊人,无疑是Machine Learning Research上最靓的仔,各种进 ...

  5. Python如何将py文件打包成exe

    安装pyinstaller 打开cmd窗口,输入pip install pyinstaller,命令行输出successfully表示成功. 生成exe文件 一.单个py文件 在py文件目录下,打开c ...

  6. 基于BIT数组实现全局功能开关

    前提 某一天巧合打开了sofa-bolt项目,查找部分源码,看到了项目中使用bit数组实现功能开关的特性,感觉这种方式可以借鉴,于是写下这篇文章. 原理 bit数组的布局如下: 由于每个bit都可以表 ...

  7. python3中匿名函数做参数,匿名函数做实参,eval关键字

    一:说到匿名函数,大家都感到陌生又熟悉,今天我带大家了解一下py3中的匿名函数,以及匿名函数作为函数的参数的情况 主要通过以下实例来说明: 实例一: newarr =[33,44444,6222,88 ...

  8. Hexo搭建静态博客站点

    什么是Hexo? Hexo 是一个快速.简洁且高效的博客框架.Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页. 本文将介绍如何在没有域名和云主机的 ...

  9. vue.js 贡献指南(翻译)

    Vue.js Contributing Guide vue 2.x 嗨! 我很高兴你有兴趣为Vue.js做贡献. 在提交您的贡献之前,请务必花点时间阅读以下指南. 行为守则 问题报告指南 PR指南 开 ...

  10. Netty入门(一):ByteBuf

    网络数据的基本单位总是字节.Java NIO 提供了 ByteBuffer 作为它的字节容器,但是这个类使用起来过于复杂,而且也有些繁琐.Netty 的 ByteBuffer 替代品是 ByteBuf ...