JAVAEE——spring03:spring整合JDBC和aop事务
一、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事务的更多相关文章
- Spring整合JDBC以及AOP管理事务
本节内容: Spring整合JDBC Spring中的AOP管理事务 一.Spring整合JDBC Spring框架永远是一个容器,Spring整合JDBC其实就是Spring提供了一个对象,这个对象 ...
- Spring整合JDBC(连接池、JDBC模板、Dao配置到Spring容器、配置文件的优化)
1.Spring整合JDBC (1)导包(共12个): c3p0连接池.JDBC驱动(4个) Spring-jdbc.Spring-tx事务(2个) (2)JDBC模板对象(JDBCTemplate) ...
- Spring整合jdbc
首先web.xml文件跟往常一样,加载spring容器和加载org.springframework.web.context.ContextLoaderListener读取applicationCont ...
- Spring整合JDBC及事务处理
1.Spring整合JDBC DAO是数据访问对象(data access object)的简写.接口是实现松耦合的关键,Spring也鼓励使用接口,但不是强制的. 捕获异常时希望能尝试从异常状态中恢 ...
- Spring整合JDBC实现简单的增删改
Spring整合JDBC实现简单的增删改: 1.导入Spring的包和数据库的驱动包: 2.选择一个数据源(dbcp和C3P0) 3.导入数据源的包(这里我们使用dbcp) <span styl ...
- Spring整合AspectJ的AOP
学而时习之,不亦说乎! --<论语> 看这一篇之前最好先看前面关于AOP的两篇. http://www.cnblogs.com/z ...
- Spring知识点总结(五)Spring整合JDBC
1. 回顾JDBC a. java操作关系型数据的API.导入相关数据库的驱动包后可以通过JDBC提供的接口来操作数据库. b. 实现JDBC的六个步骤 ...
- spring整合jdbc方法一
用了一段时间的spring这,闲来没事做一下spring整合jdbc 目录文件 导入jar包 由于spring的jar包是在myeclipse中自动导入的有些暂时用不到的也没有处理. Emp类 pac ...
- 四、spring的JDBC模板和事务管理
Spring的JDBC模板 Spring是JavaEE开发的一站式框架,对各种持久化技术都提供了简单的模板 ORM持久化技术 模板类 JDBC org.springframework.jdbc.cor ...
随机推荐
- Eclipse中启动tomcat时内存溢出
今天在启动自己项目的时候遇到一个永久带(permgen space)内存溢出,查找了很多资料和请教了许多大神,最终才解决问题. 一.什么原因造成了永久带溢出: 1.项目使用了太多的静态变量 2.加载了 ...
- Eclipse设置问题:字体大小、修改注释内容、修改快捷键
一.设置字体大小,看下图,包括了设计代码字体大小和控制台输出字体大小 二.修改注释内容 选择window---->>preferences 选择Java---->>code s ...
- 【CSS入门基础,有需要的看过来哦】心境,心静,不轻言放弃!---致CSS
整理一下近一周学习的有关CSS的基础知识笔记: CSS语法必须写在<style>标签中哦~/*注释*/ [CSS常用背景属性]background background-color:背景色 ...
- 对类对象使用new时地址分配的情况
我们知道,string类内部的构造函数是采用new来分配地址的.当创建对象时,会调用string的构造函数,从而实质上也使用了new.那么问题来了,如果我用new再创建一个string类型的指针呢?下 ...
- 关于JAVA自带MD5的方法
有空再详细解释 import java.security.MessageDigest; public class MD5 { public final static String MD51(Strin ...
- javaWeb学习总结(10)- EL函数库(2)
一.EL函数库介绍 由于在JSP页面中显示数据时,经常需要对显示的字符串进行处理,SUN公司针对于一些常见处理定义了一套EL函数库供开发者使用. 这些EL函数在JSTL开发包中进行描述,因此在JSP页 ...
- 关于win10和sqlserver的兼容性
本人主要是用.NET开发一些MIS(信息管理系统)系统,如酒店管理系统,医院管理系统,以及其附属的如餐饮管理系统,洗浴管理系统,以及医保管理系统,合疗管理系统,前期开发的产品主要是VS2008+sql ...
- 物理CPU 逻辑CPU 核数
一.概念 ① 物理CPU 实际Server中插槽上的CPU个数 物理cpu数量,可以数不重复的 physical id 有几个 ② 逻辑CPU ③ CPU核数 一块CPU上面能处理数据的芯片组的数量 ...
- 用R语言做数据清理(详细教程)
数据的清理 如同列夫托尔斯泰所说的那样:“幸福的家庭都是相似的,不幸的家庭各有各的不幸”,糟糕的恶心的数据各有各的糟糕之处,好的数据集都是相似的.一份好的,干净而整洁的数据至少包括以下几个要素: 1. ...
- React,关于redux的一点小见解
最近项目做多页面应用使用到了,react + webpack + redux + antd去构建多页面的应用,本地开发用express去模拟服务端程序(个人觉得可以换成dva).所以在这里吐槽一下我自 ...