经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » 设计模式 » 查看文章
SSH框架之Spring第四篇
来源:cnblogs  作者:小小一  时间:2019/9/23 8:54:11  对本文有异议
  1. 1.1 JdbcTemplate概述 :
  2. 它是spring框架中提供的一个对象,是对原始JdbcAPI对象的简单封装.spring框架为我们提供了很多的操作模板类.
  3. ORM持久化技术 模板类
  4. JDBC org.springframework.jdbc.core.JdbcTemplate.
  5. Hibernate3.0 org.springframework.orm.hibernate3.HibernateTemplate.
  6. IBatis(MyBatis) org.springframework.orm.ibatis.SqlMapClientTemplate.
  7. JPA org.springframework.orm.jpa.JpaTemplate.
  8. 在导包的时候需要导入spring-jdbc-4.24.RELEASF.jar,还需要导入一个spring-tx-4.2.4.RELEASE.jar(它和事务有关)
  9. <!-- 配置数据源 -->
  10. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  11. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  12. <property name="url" value="jdbc:mysql:// /spring_day04"></property>
  13. <property name="username" value="root"></property>
  14. <property name="password" value="1234"></property>
  15. </bean>
  16. 1.3.3.3配置spring内置数据源
  17. spring框架也提供了一个内置数据源,我们也可以使用spring的内置数据源,它就在spring-jdbc-4.2.4.REEASE.jar包中:
  18. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  19. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  20. <property name="url" value="jdbc:mysql:///spring_day04"></property>
  21. <property name="username" value="root"></property>
  22. <property name="password" value="1234"></property>
  23. </bean>
  24. 1.3.4将数据库连接的信息配置到属性文件中:
  25. 【定义属性文件】
  26. jdbc.driverClass=com.mysql.jdbc.Driver
  27. jdbc.url=jdbc:mysql:///spring_day02
  28. jdbc.username=root
  29. jdbc.password=123
  30. 【引入外部的属性文件】
  31. 一种方式:
  32. <!-- 引入外部属性文件: -->
  33. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  34. <property name="location" value="classpath:jdbc.properties"/>
  35. </bean>
  36. 二种方式:
  37. <context:property-placeholder location="classpath:jdbc.properties"/>
  38.  
  39. 1.4JdbcTemplate的增删改查操作
  40. 1.4.1前期准备
  41. 创建数据库:
  42. create database spring_day04;
  43. use spring_day04;
  44. 创建表:
  45. create table account(
  46. id int primary key auto_increment,
  47. name varchar(40),
  48. money float
  49. )character set utf8 collate utf8_general_ci;
  50. 1.4.2spring配置文件中配置JdbcTemplate
  51. <?xml version="1.0" encoding="UTF-8"?>
  52. <beans xmlns="http://www.springframework.org/schema/beans"
  53. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  54. xsi:schemaLocation="http://www.springframework.org/schema/beans
  55. http://www.springframework.org/schema/beans/spring-beans.xsd">
  56.  
  57. <!-- 配置一个数据库的操作模板:JdbcTemplate -->
  58. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  59. <property name="dataSource" ref="dataSource"></property>
  60. </bean>
  61. <!-- 配置数据源 -->
  62. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  63. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  64. <property name="url" value="jdbc:mysql:///spring_day04"></property>
  65. <property name="username" value="root"></property>
  66. <property name="password" value="1234"></property>
  67. </bean>
  68. </beans>
  69. 1.4.3最基本使用
  70. public class JdbcTemplateDemo2 {
  71. public static void main(String[] args) {
  72. //1.获取Spring容器
  73. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  74. //2.根据id获取bean对象
  75. JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
  76. //3.执行操作
  77. jt.execute("insert into account(name,money)values('eee',500)");
  78. }
  79. }
  80. 1.4.4保存操作
  81. public class JdbcTemplateDemo3 {
  82. public static void main(String[] args) {
  83. //1.获取Spring容器
  84. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  85. //2.根据id获取bean对象
  86. JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
  87. //3.执行操作
  88. //保存
  89. jt.update("insert into account(name,money)values(?,?)","fff",5000);
  90. }
  91. }
  92. 1.4.5更新操作
  93. public class JdbcTemplateDemo3 {
  94. public static void main(String[] args) {
  95. //1.获取Spring容器
  96. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  97. //2.根据id获取bean对象
  98. JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
  99. //3.执行操作
  100. //修改
  101. jt.update("update account set money = money-? where id = ?",300,6);
  102. }
  103. }
  104. 1.4.6删除操作
  105. public class JdbcTemplateDemo3 {
  106. public static void main(String[] args) {
  107. //1.获取Spring容器
  108. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  109. //2.根据id获取bean对象
  110. JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
  111. //3.执行操作
  112. //删除
  113. jt.update("delete from account where id = ?",6);
  114. }
  115. }
  116. 1.4.7查询所有操作
  117. public class JdbcTemplateDemo3 {
  118. public static void main(String[] args) {
  119. //1.获取Spring容器
  120. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  121. //2.根据id获取bean对象
  122. JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
  123. //3.执行操作
  124. //查询所有
  125. List<Account> accounts = jt.query("select * from account where money > ? ",
  126. new AccountRowMapper(), 500);
  127. for(Account o : accounts){
  128. System.out.println(o);
  129. }
  130. }
  131. }
  132. public class AccountRowMapper implements RowMapper<Account>{
  133. @Override
  134. public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
  135. Account account = new Account();
  136. account.setId(rs.getInt("id"));
  137. account.setName(rs.getString("name"));
  138. account.setMoney(rs.getFloat("money"));
  139. return account;
  140. }
  141. }
  142. 1.4.8查询一个操作
  143. 使用RowMapper的方式:常用的方式
  144. public class JdbcTemplateDemo3 {
  145. public static void main(String[] args) {
  146. //1.获取Spring容器
  147. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  148. //2.根据id获取bean对象
  149. JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
  150. //3.执行操作
  151. //查询一个
  152. List<Account> as = jt.query("select * from account where id = ? ",
  153. new AccountRowMapper(), 55);
  154. System.out.println(as.isEmpty()?"没有结果":as.get(0));
  155. }
  156. }
  157. 1.4.9查询返回一行一列操作
  158. public class JdbcTemplateDemo3 {
  159. public static void main(String[] args) {
  160. //1.获取Spring容器
  161. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  162. //2.根据id获取bean对象
  163. JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
  164. //3.执行操作
  165. //查询返回一行一列:使用聚合函数,在不使用group by字句时,都是返回一行一列。最长用的就是分页中获取总记录条数
  166. Integer total = jt.queryForObject("select count(*) from account where money > ? ",Integer.class,500);
  167. System.out.println(total);
  168. }
  169. }
  170. applicationContext.xml
  171. <?xml version="1.0" encoding="UTF-8"?>
  172. <beans xmlns="http://www.springframework.org/schema/beans"
  173. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  174. xmlns:context="http://www.springframework.org/schema/context"
  175. xmlns:aop="http://www.springframework.org/schema/aop"
  176. xmlns:tx="http://www.springframework.org/schema/tx"
  177. xsi:schemaLocation="http://www.springframework.org/schema/beans
  178. http://www.springframework.org/schema/beans/spring-beans.xsd
  179. http://www.springframework.org/schema/context
  180. http://www.springframework.org/schema/context/spring-context.xsd
  181. http://www.springframework.org/schema/aop
  182. http://www.springframework.org/schema/aop/spring-aop.xsd
  183. http://www.springframework.org/schema/tx
  184. http://www.springframework.org/schema/tx/spring-tx.xsd">
  185.  
  186. <!-- 使用Spring管理连接池对象,Spring内置的连接池对象 -->
  187. <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  188. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  189. <property name="url" value="jdbc:mysql:///spring_04"/>
  190. <property name="username" value="root"></property>
  191. <property name="password" value="root"></property>
  192. </bean> -->
  193. <!-- 配置数据源,使用Spring整合dbcp连接,没有导入jar -->
  194. <!-- <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
  195. <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  196. <property name="url" value="jdbc:mysql:///spring_04"/>
  197. <property name="username" value="root"/>
  198. <property name="password" value="root"/>
  199. </bean> -->
  200. <!-- 使用Spring整合c3p0的连接池,没有采用属性文件的方式 -->
  201. <!--
  202. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  203. <property name="driverClass" value="com.mysql.jdbc.Driver"/>
  204. <property name="jdbcUrl" value="jdbc:mysql:///spring_04"/>
  205. <property name="user" value="root"/>
  206. <property name="password" value="root"/>
  207. </bean> -->
  208. <!-- 使用context:property-placeholder标签,读取属性文件 -->
  209. <context:property-placeholder location="classpath:db.properties"/>
  210. <!-- 使用Spring整合c3p0的连接池,采用属性文件的方式 -->
  211. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  212. <property name="driverClass" value="${jdbc.driver}"/>
  213. <property name="jdbcUrl" value="${jdbc.url}"/>
  214. <property name="user" value="${jdbc.user}"/>
  215. <property name="password" value="${jdbc.password}"/>
  216. </bean>
  217. <!-- spring管理JbdcTemplate模板 -->
  218. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  219. <property name="dataSource" ref="dataSource"/>
  220. </bean>
  221.  
  222. </beans>
  223. db.properties : 属性文件
  224. jdbc.driver=com.mysql.jdbc.Driver
  225. jdbc.url=jdbc:mysql:///spring_day04
  226. jdbc.user=root
  227. jdbc.password=root
  228. Demo测试 :
  229. package com.ithiema.demo1;
  230. import java.sql.ResultSet;
  231. import java.sql.SQLException;
  232. import java.util.List;
  233. import javax.annotation.Resource;
  234. import org.junit.Test;
  235. import org.junit.runner.RunWith;
  236. import org.springframework.jdbc.core.JdbcTemplate;
  237. import org.springframework.jdbc.core.RowMapper;
  238. import org.springframework.test.context.ContextConfiguration;
  239. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  240. /**
  241. * Spring整合JdbcTemplate的方式入门
  242. * @author Administrator
  243. */
  244. @RunWith(SpringJUnit4ClassRunner.class)
  245. @ContextConfiguration("classpath:applicationContext.xml")
  246. public class Demo11 {
  247. @Resource(name="jdbcTemplate")
  248. private JdbcTemplate jdbcTemplate;
  249. /**
  250. * 添加
  251. */
  252. @Test
  253. public void run1(){
  254. jdbcTemplate.update("insert into account values (null,?,?)", "嘿嘿",10000);
  255. }
  256. /**
  257. * 修改
  258. */
  259. @Test
  260. public void run2(){
  261. jdbcTemplate.update("update account set name = ?,money = ? where id = ?", "嘻嘻",5000,6);
  262. }
  263. /**
  264. * 删除
  265. */
  266. @Test
  267. public void run3(){
  268. jdbcTemplate.update("delete from account where id = ?", 6);
  269. }
  270. /**
  271. * 查询多条数据
  272. */
  273. @Test
  274. public void run4(){
  275. // sql sql语句
  276. // rowMapper 提供封装数据的接口,自己提供实现类(自己封装数据的)
  277. List<Account> list = jdbcTemplate.query("select * from account", new BeanMapper());
  278. for (Account account : list) {
  279. System.out.println(account);
  280. }
  281. }
  282. }
  283. /**
  284. * 自己封装的实现类,封装数据的
  285. * @author Administrator
  286. */
  287. class BeanMapper implements RowMapper<Account>{
  288. /**
  289. * 一行一行封装数据的
  290. */
  291. public Account mapRow(ResultSet rs, int index) throws SQLException {
  292. // 创建Account对象,一个属性一个属性赋值,返回对象
  293. Account ac = new Account();
  294. ac.setId(rs.getInt("id"));
  295. ac.setName(rs.getString("name"));
  296. ac.setMoney(rs.getDouble("money"));
  297. return ac;
  298. }
  299. }
  300. 2,1 Spring 事务控制我们要明确的
  301. 1: JavaEE体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案.
  302. 2: Spring框架为我们提供就一组事务控制的接口.这组接口是在spring-tx-4.2.4RELEASE.jar中.
  303. 3: spring的事务都是基于AOP的,它既可以使用编程的方式实现,也可以使用配置的方式实现
  304. 2.2Spring中事务控制的API介绍
  305. 2.2.1PlatformTransactionManager
  306. 此接口是spring的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:
  307. 我们在开发中都是使用它的实现类,如下图:
  308. 真正管理事务的对象
  309. org.springframework.jdbc.datasource.DataSourceTransactionManager 使用Spring JDBCiBatis 进行持久化数据时使用
  310. org.springframework.orm.hibernate3.HibernateTransactionManager 使用Hibernate版本进行持久化数据时使用
  311. 2.2.2TransactionDefinition
  312. 它是事务的定义信息对象,里面有如下方法:
  313. 2.2.2.1事务的隔离级别
  314. 2.2.2.2事务的传播行为
  315. REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
  316. SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
  317. MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
  318. REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
  319. NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
  320. NEVER:以非事务方式运行,如果当前存在事务,抛出异常
  321. NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED类似的操作。
  322. 2.2.2.3超时时间
  323. 默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
  324. 2.2.2.4是否是只读事务
  325. 建议查询时设置为只读。
  326. 2.2.3TransactionStatus
  327. 此接口提供的是事务具体的运行状态,方法介绍如下图:
  328. 2.3基于XML的声明式事务控制(配置方式)重点
  329. 2.3.1环境搭建
  330. 2.3.1.1第一步:拷贝必要的jar包到工程的lib目录
  331. 2.3.1.2第二步:创建spring的配置文件并导入约束
  332. <?xml version="1.0" encoding="UTF-8"?>
  333. <beans xmlns="http://www.springframework.org/schema/beans"
  334. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  335. xmlns:aop="http://www.springframework.org/schema/aop"
  336. xmlns:tx="http://www.springframework.org/schema/tx"
  337. xsi:schemaLocation="http://www.springframework.org/schema/beans
  338. http://www.springframework.org/schema/beans/spring-beans.xsd
  339. http://www.springframework.org/schema/tx
  340. http://www.springframework.org/schema/tx/spring-tx.xsd
  341. http://www.springframework.org/schema/aop
  342. http://www.springframework.org/schema/aop/spring-aop.xsd">
  343. </beans>
  344. 2.3.1.3第三步:准备数据库表和实体类
  345. 创建数据库:
  346. create database spring_day04;
  347. use spring_day04;
  348. 创建表:
  349. create table account(
  350. id int primary key auto_increment,
  351. name varchar(40),
  352. money float
  353. )character set utf8 collate utf8_general_ci;
  354. /**
  355. * 账户的实体
  356. */
  357. public class Account implements Serializable {
  358. private Integer id;
  359. private String name;
  360. private Float money;
  361. public Integer getId() {
  362. return id;
  363. }
  364. public void setId(Integer id) {
  365. this.id = id;
  366. }
  367. public String getName() {
  368. return name;
  369. }
  370. public void setName(String name) {
  371. this.name = name;
  372. }
  373. public Float getMoney() {
  374. return money;
  375. }
  376. public void setMoney(Float money) {
  377. this.money = money;
  378. }
  379. @Override
  380. public String toString() {
  381. return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";
  382. }
  383. }
  384. 2.3.1.4第四步:编写业务层接口和实现类
  385. /**
  386. * 账户的业务层接口
  387. */
  388. public interface IAccountService {
  389. /**
  390. * 根据id查询账户信息
  391. * @param id
  392. * @return
  393. */
  394. Account findAccountById(Integer id);//
  395. /**
  396. * 转账
  397. * @param sourceName 转出账户名称
  398. * @param targeName 转入账户名称
  399. * @param money 转账金额
  400. */
  401. void transfer(String sourceName,String targeName,Float money);//增删改
  402. }
  403. /**
  404. * 账户的业务层实现类
  405. */
  406. public class AccountServiceImpl implements IAccountService {
  407. private IAccountDao accountDao;
  408. public void setAccountDao(IAccountDao accountDao) {
  409. this.accountDao = accountDao;
  410. }
  411. @Override
  412. public Account findAccountById(Integer id) {
  413. return accountDao.findAccountById(id);
  414. }
  415. @Override
  416. public void transfer(String sourceName, String targeName, Float money) {
  417. //1.根据名称查询两个账户
  418. Account source = accountDao.findAccountByName(sourceName);
  419. Account target = accountDao.findAccountByName(targeName);
  420. //2.修改两个账户的金额
  421. source.setMoney(source.getMoney()-money);//转出账户减钱
  422. target.setMoney(target.getMoney()+money);//转入账户加钱
  423. //3.更新两个账户
  424. accountDao.updateAccount(source);
  425. int i=1/0;
  426. accountDao.updateAccount(target);
  427. }
  428. }
  429. 2.3.1.5第五步:编写Dao接口和实现类
  430. /**
  431. * 账户的持久层接口
  432. */
  433. public interface IAccountDao {
  434. /**
  435. * 根据id查询账户信息
  436. * @param id
  437. * @return
  438. */
  439. Account findAccountById(Integer id);
  440. /**
  441. * 根据名称查询账户信息
  442. * @return
  443. */
  444. Account findAccountByName(String name);
  445. /**
  446. * 更新账户信息
  447. * @param account
  448. */
  449. void updateAccount(Account account);
  450. }
  451. /**
  452. * 账户的持久层实现类
  453. * 此版本dao,只需要给它的父类注入一个数据源
  454. */
  455. public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
  456. @Override
  457. public Account findAccountById(Integer id) {
  458. List<Account> list = getJdbcTemplate().query("select * from account where id = ? ",new AccountRowMapper(),id);
  459. return list.isEmpty()?null:list.get(0);
  460. }
  461. @Override
  462. public Account findAccountByName(String name) {
  463. List<Account> list = getJdbcTemplate().query("select * from account where name = ? ",new AccountRowMapper(),name);
  464. if(list.isEmpty()){
  465. return null;
  466. }
  467. if(list.size()>1){
  468. throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
  469. }
  470. return list.get(0);
  471. }
  472. @Override
  473. public void updateAccount(Account account) {
  474. getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
  475. }
  476. }
  477. /**
  478. * 账户的封装类RowMapper的实现类
  479. */
  480. public class AccountRowMapper implements RowMapper<Account>{
  481. @Override
  482. public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
  483. Account account = new Account();
  484. account.setId(rs.getInt("id"));
  485. account.setName(rs.getString("name"));
  486. account.setMoney(rs.getFloat("money"));
  487. return account;
  488. }
  489. }
  490. 2.3.1.6第六步:在配置文件中配置业务层和持久层对
  491. <!-- 配置service -->
  492. <bean id="accountService" class="com.baidu.service.impl.AccountServiceImpl">
  493. <property name="accountDao" ref="accountDao"></property>
  494. </bean>
  495. <!-- 配置dao -->
  496. <bean id="accountDao" class="com.baidu.dao.impl.AccountDaoImpl">
  497. <!-- 注入dataSource -->
  498. <property name="dataSource" ref="dataSource"></property>
  499. </bean>
  500. <!-- 配置数据源 -->
  501. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  502. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  503. <property name="url" value="jdbc:mysql:///spring_day04"></property>
  504. <property name="username" value="root"></property>
  505. <property name="password" value="1234"></property>
  506. </bean>
  507. 2.3.2配置步骤
  508. 2.3.2.1第一步:配置事务管理器
  509. <!-- 配置一个事务管理器 -->
  510. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  511. <!-- 注入DataSource -->
  512. <property name="dataSource" ref="dataSource"></property>
  513. </bean>
  514. 2.3.2.2第二步:配置事务的通知引用事务管理器
  515. <!-- 事务的配置 -->
  516. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  517. </tx:advice>
  518. 2.3.2.3第三步:配置事务的属性
  519. <!--在tx:advice标签内部 配置事务的属性 -->
  520. <tx:attributes>
  521. <!-- 指定方法名称:是业务核心方法
  522. read-only:是否是只读事务。默认false,不只读。
  523. isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
  524. propagation:指定事务的传播行为。
  525. timeout:指定超时时间。默认值为:-1。永不超时。
  526. rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。没有默认值,任何异常都回滚。
  527. no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,任何异常都回滚。
  528. -->
  529. <tx:method name="*" read-only="false" propagation="REQUIRED"/>
  530. <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
  531. </tx:attributes>
  532. 2.3.2.4第四步:配置AOP-切入点表达式
  533. <!-- 配置aop -->
  534. <aop:config>
  535. <!-- 配置切入点表达式 -->
  536. <aop:pointcut expression="execution(* com.baidu.service.impl.*.*(..))" id="pt1"/>
  537. </aop:config>
  538. 2.3.2.5第五步:配置切入点表达式和事务通知的对应关系
  539. <!-- aop:config标签内部:建立事务的通知和切入点表达式的关系 -->
  540. <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
  541. 2.4基于XML和注解组合使用的整合方式
  542. 2.4.1环境搭建
  543. 2.4.1.1第一步:拷贝必备的jar包到工程的lib目录
  544. 2.4.1.2第二步:创建spring的配置文件导入约束并配置扫描的包
  545. <?xml version="1.0" encoding="UTF-8"?>
  546. <beans xmlns="http://www.springframework.org/schema/beans"
  547. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  548. xmlns:aop="http://www.springframework.org/schema/aop"
  549. xmlns:tx="http://www.springframework.org/schema/tx"
  550. xmlns:context="http://www.springframework.org/schema/context"
  551. xsi:schemaLocation="http://www.springframework.org/schema/beans
  552. http://www.springframework.org/schema/beans/spring-beans.xsd
  553. http://www.springframework.org/schema/tx
  554. http://www.springframework.org/schema/tx/spring-tx.xsd
  555. http://www.springframework.org/schema/aop
  556. http://www.springframework.org/schema/aop/spring-aop.xsd
  557. http://www.springframework.org/schema/context
  558. http://www.springframework.org/schema/context/spring-context.xsd">
  559. <!-- 配置spring要扫描的包 -->
  560. <context:component-scan base-package="com.baidu"></context:component-scan>
  561. </beans>
  562. 2.4.1.3第三步:创建数据库表和实体类
  563. 和基于xml的配置相同。
  564. 2.4.1.4第四步:创建业务层接口和实现类并使用注解让spring管理
  565. 业务层接口和基于xml配置的时候相同。略
  566. /**
  567. * 账户的业务层实现类
  568. */
  569. @Service("accountService")
  570. public class AccountServiceImpl implements IAccountService {
  571. @Autowired
  572. private IAccountDao accountDao;
  573. @Override
  574. public Account findAccountById(Integer id) {
  575. return accountDao.findAccountById(id);
  576. }
  577. @Override
  578. public void transfer(String sourceName, String targeName, Float money) {
  579. //1.根据名称查询两个账户
  580. Account source = accountDao.findAccountByName(sourceName);
  581. Account target = accountDao.findAccountByName(targeName);
  582. //2.修改两个账户的金额
  583. source.setMoney(source.getMoney()-money);//转出账户减钱
  584. target.setMoney(target.getMoney()+money);//转入账户加钱
  585. //3.更新两个账户
  586. accountDao.updateAccount(source);
  587. int i=1/0;
  588. accountDao.updateAccount(target);
  589. }
  590. }
  591. 2.4.1.5第五步:创建Dao接口和实现类并使用注解让spring管理
  592. Dao层接口和AccountRowMapper与基于xml配置的时候相同。略
  593. @Repository("accountDao")
  594. public class AccountDaoImpl implements IAccountDao {
  595. @Autowired
  596. private JdbcTemplate jdbcTemplate;
  597. @Override
  598. public Account findAccountById(Integer id) {
  599. List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
  600. return list.isEmpty()?null:list.get(0);
  601. }
  602. @Override
  603. public Account findAccountByName(String name) {
  604. List<Account> list = jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
  605. if(list.isEmpty()){
  606. return null;
  607. }
  608. if(list.size()>1){
  609. throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
  610. }
  611. return list.get(0);
  612. }
  613. @Override
  614. public void updateAccount(Account account) {
  615. jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
  616. }
  617. }
  618. 2.4.2配置步骤
  619. 2.4.2.1第一步:配置数据源和JdbcTemplate
  620. <!-- 配置数据源 -->
  621. <bean id="dataSource"
  622. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  623. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  624. <property name="url" value="jdbc:mysql:///spring_day04"></property>
  625. <property name="username" value="root"></property>
  626. <property name="password" value="1234"></property>
  627. </bean>
  628.  
  629.  
  630. 2.4.2.2第二步:配置事务管理器并注入数据源
  631. <!-- 配置JdbcTemplate -->
  632. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  633. <property name="dataSource" ref="dataSource"></property>
  634. </bean>
  635. 2.4.2.3第三步:在业务层使用@Transactional注解
  636. @Service("accountService")
  637. @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
  638. public class AccountServiceImpl implements IAccountService {
  639. @Autowired
  640. private IAccountDao accountDao;
  641. @Override
  642. public Account findAccountById(Integer id) {
  643. return accountDao.findAccountById(id);
  644. }
  645. @Override
  646. @Transactional(readOnly=false,propagation=Propagation.REQUIRED)
  647. public void transfer(String sourceName, String targeName, Float money) {
  648. //1.根据名称查询两个账户
  649. Account source = accountDao.findAccountByName(sourceName);
  650. Account target = accountDao.findAccountByName(targeName);
  651. //2.修改两个账户的金额
  652. source.setMoney(source.getMoney()-money);//转出账户减钱
  653. target.setMoney(target.getMoney()+money);//转入账户加钱
  654. //3.更新两个账户
  655. accountDao.updateAccount(source);
  656. //int i=1/0;
  657. accountDao.updateAccount(target);
  658. }
  659. }
  660. 该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
  661. 出现接口上,表示该接口的所有实现类都有事务支持。
  662. 出现在类上,表示类中所有方法有事务支持
  663. 出现在方法上,表示方法有事务支持。
  664. 以上三个位置的优先级:方法>类>接口
  665. 2.4.2.4第四步:在配置文件中开启spring对注解事务的支持
  666. <!-- 开启spring对注解事务的支持 -->
  667. <tx:annotation-driven transaction-manager="transactionManager"/>
  668. 2.5基于纯注解的声明式事务控制(配置方式)重点
  669. 2.5.1环境搭建
  670. 2.5.1.1第一步:拷贝必备的jar包到工程的lib目录
  671. 2.5.1.2第二步:创建一个类用于加载spring的配置并指定要扫描的包
  672. /**
  673. * 用于初始化spring容器的配置类
  674. */
  675. @Configuration
  676. @ComponentScan(basePackages="com.baidu")
  677. public class SpringConfiguration {
  678. }
  679. 2.5.1.3第三步:创建数据库表和实体类
  680. 和基于xml的配置相同。略
  681. 2.5.1.4第四步:创建业务层接口和实现类并使用注解让spring管理
  682. 业务层接口和基于xml配置的时候相同。略
  683. /**
  684. * 账户的业务层实现类
  685. */
  686. @Service("accountService")
  687. public class AccountServiceImpl implements IAccountService {
  688. @Autowired
  689. private IAccountDao accountDao;
  690. @Override
  691. public Account findAccountById(Integer id) {
  692. return accountDao.findAccountById(id);
  693. }
  694. @Override
  695. public void transfer(String sourceName, String targeName, Float money) {
  696. //1.根据名称查询两个账户
  697. Account source = accountDao.findAccountByName(sourceName);
  698. Account target = accountDao.findAccountByName(targeName);
  699. //2.修改两个账户的金额
  700. source.setMoney(source.getMoney()-money);//转出账户减钱
  701. target.setMoney(target.getMoney()+money);//转入账户加钱
  702. //3.更新两个账户
  703. accountDao.updateAccount(source);
  704. int i=1/0;
  705. accountDao.updateAccount(target);
  706. }
  707. }
  708. 2.5.1.5第五步:创建Dao接口和实现类并使用注解让spring管理
  709. Dao层接口和AccountRowMapper与基于xml配置的时候相同。略
  710. @Repository("accountDao")
  711. public class AccountDaoImpl implements IAccountDao {
  712. @Autowired
  713. private JdbcTemplate jdbcTemplate;
  714. @Override
  715. public Account findAccountById(Integer id) {
  716. List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
  717. return list.isEmpty()?null:list.get(0);
  718. }
  719. @Override
  720. public Account findAccountByName(String name) {
  721. List<Account> list = jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
  722. if(list.isEmpty()){
  723. return null;
  724. }
  725. if(list.size()>1){
  726. throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
  727. }
  728. return list.get(0);
  729. }
  730. @Override
  731. public void updateAccount(Account account) {
  732. jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
  733. }
  734. }
  735. 2.5.2配置步骤
  736. 2.5.2.1第一步:使用@Bean注解配置数据源
  737. @Bean(name = "dataSource")
  738. public DataSource createDS() throws Exception {
  739. DriverManagerDataSource dataSource = new DriverManagerDataSource();
  740. dataSource.setUsername("root");
  741. dataSource.setPassword("123");
  742. dataSource.setDriverClassName("com.mysql.jdbc.Driver");
  743. dataSource.setUrl("jdbc:mysql:///spring3_day04");
  744. return dataSource;
  745. }
  746. 2.5.2.2第二步:使用@Bean注解配置配置事务管理器
  747. @Bean
  748. public PlatformTransactionManager
  749. createTransactionManager(@Qualifier("dataSource") DataSource dataSource) {
  750. return new DataSourceTransactionManager(dataSource);
  751. }
  752. 2.5.2.3第三步:使用@Bean注解配置JdbcTemplate
  753. @Bean
  754. public JdbcTemplate createTemplate(@Qualifier("dataSource") DataSource dataSource)
  755. {
  756. return new JdbcTemplate(dataSource);
  757. }
  758. 2.5.2.4第四步:在需要控制事务的业务层实现类上使用@Transactional注解
  759. @Service("accountService")
  760. @Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
  761. public class AccountServiceImpl implements IAccountService {
  762. @Autowired
  763. private IAccountDao accountDao;
  764. @Override
  765. public Account findAccountById(Integer id) {
  766. return accountDao.findAccountById(id);
  767. }
  768. @Override
  769. @Transactional(readOnly=false,propagation=Propagation.REQUIRED)
  770. public void transfer(String sourceName, String targeName, Float money) {
  771. //1.根据名称查询两个账户
  772. Account source = accountDao.findAccountByName(sourceName);
  773. Account target = accountDao.findAccountByName(targeName);
  774. //2.修改两个账户的金额
  775. source.setMoney(source.getMoney()-money);//转出账户减钱
  776. target.setMoney(target.getMoney()+money);//转入账户加钱
  777. //3.更新两个账户
  778. accountDao.updateAccount(source);
  779. //int i=1/0;
  780. accountDao.updateAccount(target);
  781. }
  782. }
  783. 该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上。
  784. 出现接口上,表示该接口的所有实现类都有事务支持。
  785. 出现在类上,表示类中所有方法有事务支持
  786. 出现在方法上,表示方法有事务支持。
  787. 以上三个位置的优先级:方法>类>接口。
  788. 2.5.2.5第五步:使用@EnableTransactionManagement开启spring对注解事务的的支持
  789. @Configuration
  790. @EnableTransactionManagement
  791. public class SpringTxConfiguration {
  792. //里面配置数据源,配置JdbcTemplate,配置事务管理器。在之前的步骤已经写过了。
  793. }
  794. Spring中开启事务的案例
  795. applicationContext3.xml
  796. <?xml version="1.0" encoding="UTF-8"?>
  797. <beans xmlns="http://www.springframework.org/schema/beans"
  798. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  799. xmlns:context="http://www.springframework.org/schema/context"
  800. xmlns:aop="http://www.springframework.org/schema/aop"
  801. xmlns:tx="http://www.springframework.org/schema/tx"
  802. xsi:schemaLocation="http://www.springframework.org/schema/beans
  803. http://www.springframework.org/schema/beans/spring-beans.xsd
  804. http://www.springframework.org/schema/context
  805. http://www.springframework.org/schema/context/spring-context.xsd
  806. http://www.springframework.org/schema/aop
  807. http://www.springframework.org/schema/aop/spring-aop.xsd
  808. http://www.springframework.org/schema/tx
  809. http://www.springframework.org/schema/tx/spring-tx.xsd">
  810. <!-- 使用Spring整合c3p0的连接池,没有采用属性文件的方式 -->
  811. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource ">
  812. <property name="driverClass" value="com.mysql.jdbc.Driver"/>
  813. <property name="jdbcUrl" value="jdbc:mysql:///spring_04"/>
  814. <property name="user" value="root"/>
  815. <property name="password" value="root"/>
  816. </bean>
  817. <!-- 配置平台事务管理器 -->
  818. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  819. <property name="dataSource" ref="dataSource"></property>
  820. </bean>
  821. <!-- 配置通知: Spring框架提供通知,不是咋们自己编写的 -->
  822. <tx:advice id="myAdvice" transaction-manager="transactionManager">
  823. <tx:attributes>
  824. <!-- 给具体的业务层的方法进行隔离级别,传播行为的具体的配置 -->
  825. <tx:method name="pay" isolation="DEFAULT" propagation="REQUIRED"/>
  826. <tx:method name="save*" isolation="DEFAULT"></tx:method>
  827. <tx:method name="find*" read-only="true"></tx:method>
  828. </tx:attributes>
  829. </tx:advice>
  830. <!-- 配置AOP的增强 -->
  831. <aop:config>
  832. <!-- Spring框架制作的通知,必须要使用该标签,如果是自定义的切面,使用aop:aspect标签 -->
  833. <aop:advisor advice-ref="myAdvice" pointcut="execution(public * com.baidu.*.*ServiceImpl.*(..))"></aop:advisor>
  834. </aop:config>
  835. <!-- 可以注入连接池 -->
  836. <bean id="accountDao" class="com.baidu.demo3.AccountDaoImpl">
  837. <property name="dataSource" ref="dataSource"></property>
  838. </bean>
  839. <!-- 管理service -->
  840. <bean id="accountService" class="com.baidu.demo3.AccountServiceImpl">
  841. <property name="accountDao" ref="accountDao"></property>
  842. </bean>
  843. </beans>
  844. dao层对代码进行了优化,优化了JdbcTemplate
  845. public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
  846. /*
  847. private JdbcTemplate jdbcTemplate;
  848. public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
  849. this.jdbcTemplate = jdbcTemplate;
  850. }*/
  851. //减钱
  852. @Override
  853. public void outMoney(String out, double money) {
  854. //jdbcTemplate.update("update username set money = money - ? where name = ?",money,out);
  855. this.getJdbcTemplate().update("update username set money = money - ? where name=?",money,out);
  856. }
  857. //加钱
  858. @Override
  859. public void inMoney(String in, double money) {
  860. //jdbcTemplate.update("update username set money = money + ? where name = ?",money,in);
  861. this.getJdbcTemplate().update("update username set money = money + ? where name=?",money,in);
  862. }
  863. }
  864. Xml和注解一起进行Spring的事务管理
  865. applicationContext4.xml
  866. <?xml version="1.0" encoding="UTF-8"?>
  867. <beans xmlns="http://www.springframework.org/schema/beans"
  868. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  869. xmlns:context="http://www.springframework.org/schema/context"
  870. xmlns:aop="http://www.springframework.org/schema/aop"
  871. xmlns:tx="http://www.springframework.org/schema/tx"
  872. xsi:schemaLocation="http://www.springframework.org/schema/beans
  873. http://www.springframework.org/schema/beans/spring-beans.xsd
  874. http://www.springframework.org/schema/context
  875. http://www.springframework.org/schema/context/spring-context.xsd
  876. http://www.springframework.org/schema/aop
  877. http://www.springframework.org/schema/aop/spring-aop.xsd
  878. http://www.springframework.org/schema/tx
  879. http://www.springframework.org/schema/tx/spring-tx.xsd">
  880. <!-- 开启注解的扫描 -->
  881. <context:component-scan base-package="com.baidu"/>
  882. <!-- 使用Spring整合c3p0的连接池,没有采用属性文件的方式 -->
  883. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  884. <property name="driverClass" value="com.mysql.jdbc.Driver"/>
  885. <property name="jdbcUrl" value="jdbc:mysql:///spring_04"/>
  886. <property name="user" value="root"/>
  887. <property name="password" value="root"/>
  888. </bean>
  889. <!-- 配置JdbcTemplate模板 -->
  890. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  891. <property name="dataSource" ref="dataSource"></property>
  892. </bean>
  893. <!-- 配置平台事务管理器 -->
  894. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  895. <property name="dataSource" ref="dataSource"></property>
  896. </bean>
  897. <!-- 开启事务注解 -->
  898. <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
  899. </beans>
  900. Service层用注解 :
  901. //实现类
  902. @Service("accountService")
  903. @Transactional(isolation=Isolation.DEFAULT)
  904. public class AccountServiceImpl implements AccountService {
  905. @Resource(name="accountDao")
  906. private AccountDao accountDao;
  907. // public void setAccountDao(AccountDao accountDao) {
  908. // this.accountDao = accountDao;
  909. // }
  910. //支付的方法
  911. @Override
  912. public void pay(String out, String in, double money) {
  913. //模拟两个操作
  914. //减钱
  915. accountDao.outMoney(out, money);
  916. //模拟异常
  917. //int i = 10/0;
  918. accountDao.inMoney(in, money);
  919. }
  920. }
  921. 使用纯注解的方式进行Spring事务管理 :
  922. /*
  923. * 配置类,Spring声明式事务管理,纯注解的方式
  924. *
  925. */
  926. @Configuration
  927. @ComponentScan(basePackages="com.baidu.demo5")
  928. @EnableTransactionManagement //纯注解的方式,开启事务注解
  929. public class SpringConfig {
  930. @Bean(name="dataSource")
  931. public DataSource createDataSource() throws Exception{
  932. ComboPooledDataSource dataSource = new ComboPooledDataSource();
  933. dataSource.setDriverClass("com.mysql.jdbc.Driver");
  934. dataSource.setJdbcUrl("jdbc:mysql:///spring_04");
  935. dataSource.setUser("root");
  936. dataSource.setPassword("root");
  937. return dataSource;
  938. }
  939. //把dataSource注入进来
  940. @Bean(name="jdbcTemplate")
  941. @Resource(name="dataSource")
  942. public JdbcTemplate createJdbcTemplate(DataSource dataSource) {
  943. return new JdbcTemplate(dataSource);
  944. }
  945. //创建平台事务管理器对象
  946. @Bean(name="transactionManager")
  947. @Resource(name="dataSource")
  948. public PlatformTransactionManager createTransactionManager(DataSource dataSource) {
  949. return new DataSourceTransactionManager(dataSource);
  950. }
  951. }
  952. 1 : 传播行为 : 解决业务层方法之间互相调用的问题.
  953. 传播行为的默认值 : 保证saveupdate方法在同一个事务中.
  954. 2 : Spring事务管理 : (1) : XML配置文件 ; (2) : XML+注解配置文件 ; (3) : 纯注解
  955. Spring框架提供了接口和实现类,进行事务管理的.
  956. PlatformTransactionManager接口 : 平台事务管理器,提供和回滚事务的.
  957. HibernateTransactionManager : hibernate框架事务管理的实现类.
  958. DataSourceTransactionManager : 使用JDBC或者MyBattis框架
  959. TransactionDefinition接口 : 事务的定义的信息.提供很多常量,分别表示隔离级别,传播行为.
  960. 传播行为 : 事务的传播行为,解决service方法之间的调用的问题.
  961. Spring声明式事务管理,使用AOP技术进行事务管理.
  962. 通知/增强 : 事务管理的方法,不用咋们自己编写.需要配置.
  963. 连接池 DataSource ,存在Connection ,使用JDBC进行事务管理 ,conn.commit()
  964. |
  965. |注入
  966. 平台事务管理器(必须配置的),是Spring提供接口,提交和回滚事务
  967. |
  968. |注入
  969. 自己编写通知方法(事务管理),Spring提供通知,配置通知
  970. |
  971. |注入
  972. 配置AOP增强 aop:config

 

原文链接:http://www.cnblogs.com/haizai/p/11568796.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号