一、spring整合JDBC

  1.spring提供了很多模板整合Dao技术

  

  2.spring中提供了一个可以操作数据库的对象.对象封装了jdbc技术.

   JDBCTemplate => JDBC模板对象

   与DBUtils中的QueryRunner非常相似.

        //0 准备连接池
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///xieyupeng");
dataSource.setUser("root");
dataSource.setPassword("1234");
//1 创建JDBC模板对象
JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);
//2 书写sql,并执行
String sql = "insert into t_user values(null,'rose') ";
jt.update(sql);

  3.整合步骤

   3.1 导包

   4+2:4代表:

   2代表:com.springsource.org.apache.commons.logging-1.1.1.jar、com.springsource.org.apache.log4j-1.2.15.jar(老版本要导入的,导入可以保证一定能运行)

   spring-test、spring-aop、junit4类库

   c3p0连接池、JDBC驱动

   spring-jdbc、spring-tx事务

   3.2 准备数据库(两个字段id(自增长)和name即可)

   3.3 书写Dao

//使用JDBC模板实现增删改查
public class UserDaoImpl extends JdbcDaoSupport implements UserDao {
@Override
public void save(User u) {
String sql = "insert into t_user values(null,?) ";
super.getJdbcTemplate().update(sql, u.getName());
}
@Override
public void delete(Integer id) {
String sql = "delete from t_user where id = ? ";
super.getJdbcTemplate().update(sql,id);
}
@Override
public void update(User u) {
String sql = "update t_user set name = ? where id=? ";
super.getJdbcTemplate().update(sql, u.getName(),u.getId());
}
@Override
public User getById(Integer id) {
String sql = "select * from t_user where id = ? ";
return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
return u;
}}, id); }
@Override
public int getTotalCount() {
String sql = "select count(*) from t_user ";
Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
return count;
} @Override
public List<User> getAll() {
String sql = "select * from t_user ";
List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u = new User();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
return u;
}});
return list;
}
}

   3.4 spring配置

   依赖关系

<!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
<property name="driverClass" value="${jdbc.driverClass}" ></property>
<property name="user" value="${jdbc.user}" ></property>
<property name="password" value="${jdbc.password}" ></property>
</bean> <!-- 2.将JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource" ></property>
</bean> <!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
<!-- <property name="jt" ref="jdbcTemplate" ></property> -->
<property name="dataSource" ref="dataSource" ></property>
</bean>

   3.5 测试

//演示JDBC模板
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Demo {
@Resource(name="userDao")
private UserDao ud; @Test
public void fun2() throws Exception{
User u = new User();
u.setName("tom");
ud.save(u);
}
@Test
public void fun3() throws Exception{
User u = new User();
u.setId(2);
u.setName("jack");
ud.update(u); } @Test
public void fun4() throws Exception{
ud.delete(2);
} @Test
public void fun5() throws Exception{
System.out.println(ud.getTotalCount());
} @Test
public void fun6() throws Exception{
System.out.println(ud.getById(1));
} @Test
public void fun7() throws Exception{
System.out.println(ud.getAll());
} }

  4.进阶内容

   4.1 JDBCDaoSupport

public class UserDaoImpl extends JdbcDaoSupport

<!-- 3.将UserDao放入spring容器(继承JDBCDaoSupport,直接注入dataSourse即可) -->
<bean name="userDao" class="cn.itcast.a_jdbctemplate.UserDaoImpl" >
<!-- <property name="jt" ref="jdbcTemplate" ></property> -->
<property name="dataSource" ref="dataSource" ></property>
</bean>

   4.1 读取外部的Properties配置

   db.properties 注意加前缀(更好区分,防止重名)

jdbc.jdbcUrl=jdbc:mysql:///hibernate_32
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234
<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties" /> <!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
<property name="driverClass" value="${jdbc.driverClass}" ></property>
<property name="user" value="${jdbc.user}" ></property>
<property name="password" value="${jdbc.password}" ></property>
</bean>

二、使用注解配置spring

  1.事务回顾

   事务特性:acid

   事务并发问题:脏读、不可重复读、幻读

   事务的隔离级别:1 读未提交、2 读已提交、4 可重复读、8 串行化

  2.spring封装了事务管理代码

   事务操作:打开事务、提交事务、回滚事务

   事务操作对象

   因为在不同平台,操作事务的代码各不相同.spring提供了一个接口

   2.1  PlatformTransactionManager 接口

   DataSourceTransactionManager

   HibernateTransitionmanager

   注意:在spring中玩事务管理.最为核心的对象就是TransactionManager对象

   2.2  spring管理事务的属性介绍

   事务的隔离级别:1 读未提交、2 读已提交、4 可重复读、8 串行化

   是否只读:true 只读、false 可操作

   事务的传播行为:

  

  3.spring管理事务方式

  

   3.1 编码式(了解)

   3.1.1 将核心事务管理器配置到spring容器

<!-- 事务核心管理器,封装了所有事务操作. 依赖于连接池 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="dataSource" ></property>
</bean>

   3.1.2 配置TransactionTemplate模板

<!-- 事务模板对象 -->
<bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate" >
<property name="transactionManager" ref="transactionManager" ></property>
</bean>

   3.1.3 将事务模板注入Service

<!-- 3.Service-->
<bean name="accountService" class="cn.itcast.service.AccountServiceImpl" >
<property name="ad" ref="accountDao" ></property>
<property name="tt" ref="transactionTemplate" ></property>
</bean>

   3.1.4 在Service中调用模板

    public void transfer(final Integer from,final Integer to,final Double money) {

        tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus arg0) {
//减钱
ad.decreaseMoney(from, money);
int i = 1/0;//触发错误,验证代码是否正确
//加钱
ad.increaseMoney(to, money);
}
});
}

   3.2 xml配置(aop)

   3.2.1 导包

   aop、aspect、aop联盟和weaving织入包

   3.2.2 导入新的约束(tx)

  

   beans: 最基本
   context:读取properties配置
   aop:配置aop
   tx:配置事务通知

   3.2.3 配置通知

<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes>
<!-- 以方法为单位,指定方法应用什么事务属性
isolation:隔离级别
propagation:传播行为
read-only:是否只读
-->
<tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
<tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
</tx:attributes>
</tx:advice>

   3.2.4 配置将通知织入目标

<!-- 配置织入 -->
<aop:config >
<!-- 配置切点表达式 -->
<aop:pointcut expression="execution(* cn.itcast.service.*ServiceImpl.*(..))" id="txPc"/>
<!-- 配置切面 : 通知+切点
advice-ref:通知的名称
pointcut-ref:切点的名称
-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc" />
</aop:config>

   3.3 注解配置(aop)

   导包、tx约束和xml配置(aop)相同

   3.3.1 开启注解管理事务

<!-- 开启使用注解管理aop事务 -->
<tx:annotation-driven/>

   3.3.2 使用注解

@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=true)
public class AccountServiceImpl implements AccountService { private AccountDao ad ;
private TransactionTemplate tt; @Override
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)
public void transfer(final Integer from,final Integer to,final Double money) {

JAVAEE——spring03:spring整合JDBC和aop事务的更多相关文章

  1. Spring整合JDBC以及AOP管理事务

    本节内容: Spring整合JDBC Spring中的AOP管理事务 一.Spring整合JDBC Spring框架永远是一个容器,Spring整合JDBC其实就是Spring提供了一个对象,这个对象 ...

  2. Spring整合JDBC(连接池、JDBC模板、Dao配置到Spring容器、配置文件的优化)

    1.Spring整合JDBC (1)导包(共12个): c3p0连接池.JDBC驱动(4个) Spring-jdbc.Spring-tx事务(2个) (2)JDBC模板对象(JDBCTemplate) ...

  3. Spring整合jdbc

    首先web.xml文件跟往常一样,加载spring容器和加载org.springframework.web.context.ContextLoaderListener读取applicationCont ...

  4. Spring整合JDBC及事务处理

    1.Spring整合JDBC DAO是数据访问对象(data access object)的简写.接口是实现松耦合的关键,Spring也鼓励使用接口,但不是强制的. 捕获异常时希望能尝试从异常状态中恢 ...

  5. Spring整合JDBC实现简单的增删改

    Spring整合JDBC实现简单的增删改: 1.导入Spring的包和数据库的驱动包: 2.选择一个数据源(dbcp和C3P0) 3.导入数据源的包(这里我们使用dbcp) <span styl ...

  6. Spring整合AspectJ的AOP

    学而时习之,不亦说乎!                              --<论语> 看这一篇之前最好先看前面关于AOP的两篇. http://www.cnblogs.com/z ...

  7. Spring知识点总结(五)Spring整合JDBC

     1. 回顾JDBC        a. java操作关系型数据的API.导入相关数据库的驱动包后可以通过JDBC提供的接口来操作数据库.        b. 实现JDBC的六个步骤          ...

  8. spring整合jdbc方法一

    用了一段时间的spring这,闲来没事做一下spring整合jdbc 目录文件 导入jar包 由于spring的jar包是在myeclipse中自动导入的有些暂时用不到的也没有处理. Emp类 pac ...

  9. 四、spring的JDBC模板和事务管理

    Spring的JDBC模板 Spring是JavaEE开发的一站式框架,对各种持久化技术都提供了简单的模板 ORM持久化技术 模板类 JDBC org.springframework.jdbc.cor ...

随机推荐

  1. 使用maven根据JSON文件自动生成Java POJO类(Java Bean)源文件

    根据JSON文件自动生成Java POJO类(Java Bean)源文件 本文介绍使用程序jsonschema2pojo来自动生成Java的POJO类源文件,本文主要使用maven,其他构建工具请参考 ...

  2. Redis学习-Sentinel

    Redis的Sentinel系统用于管理多个Redis服务器(instance), 该系统执行以下三个任务: 监控(Monitoring):Sentinel会不断地检查你的主服务器和从服务器是否运作正 ...

  3. 基于DotNet Core的RPC框架(一) DotBPE.RPC快速开始

    0x00 简介 DotBPE.RPC是一款基于dotnet core编写的RPC框架,而它的爸爸DotBPE,目标是实现一个开箱即用的微服务框架,但是它还差点意思,还仅仅在构思和尝试的阶段.但不管怎么 ...

  4. DDD领域驱动之干货(三)完结篇!

    首先这里发一下结构图,因为是重写的,但是代码都是一样所有如下: 这里我先说一下看了大部分的DDD文章都是采用的WCF做服务,这里呢我用的是webapi做服务,WCF和WEBAPI的区别可以去百度下. ...

  5. Java内存数据模型

    本篇文章带来的是对Java内存数据模型的介绍,这对于我们深入理解Jvm虚拟机工作的原理和Java内存的划分大有裨益,好了,为了让我们理解的更为深刻,我们将会加入图片辅助的方法去理解. 本篇博文的目录: ...

  6. Swoole笔记(三)

    WebSocket 使用Swoole可以很简单的搭建异步非阻塞多进程的WebSocket服务器. WebSocket服务器 <?php $server = new swoole_websocke ...

  7. javaSE_06Java中的数组(array)

    1.什么是数组? 顾名思义,即为数据的组合或集合,数组就是用来表示一组数据的. 比如没有数组之前,我们要存储多个姓名的信息 String name1; String name2; String nam ...

  8. docker dead but pid file exists 问题

    You may have to enable the public_ol6_latest repo in order to get this package. sudo yum-config-mana ...

  9. 在.net下打造mongoDb基于官方驱动最新版本

    还是一如既往先把结构图放出来,上上个版本添加了redis的缓存,但是不满足我的需求,因为公司有项目要求是分布式所以呢,这里我就增加了mongoDb进行缓存分布式,好了先看结构图. 总的来说比较蛋疼,因 ...

  10. css3的学习

    已经学习css3一个月了,通过对css3的深入学习,我对网页设计的理解就更深刻了,以前只会用简单的图片,定位等来制作网页,现在可以运用css3扩展的新内容来写出更好看的网页. css3扩展内容中,我认 ...