码迷,mamicode.com
首页 > 编程语言 > 详细

Spring框架进阶3

时间:2018-09-10 10:58:26      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:list   err   流程   oca   min   实体   poi   准备   color   

Spring框架进阶3

测试spring_jdbc和spring对事务的管理

技术分享图片

先配置相应的pom

技术分享图片
  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0"
  3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <modelVersion>4.0.0</modelVersion>
  6 
  7     <groupId>com.spring</groupId>
  8     <artifactId>spring_3</artifactId>
  9     <version>1.0-SNAPSHOT</version>
 10 
 11     <!-- 属性 -->
 12     <properties>
 13         <!-- 设置编译版本为1.7 -->
 14         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 15         <maven.compiler.source>1.7</maven.compiler.source>
 16         <maven.compiler.target>1.7</maven.compiler.target>
 17         <!-- 可以绑定版本号 -->
 18         <spring.version>4.3.5.RELEASE</spring.version>
 19     </properties>
 20 
 21     <!-- 锁定版本,struts2-2.3.24、spring4.2.4、hibernate5.0.7 -->
 22     <dependencyManagement>
 23         <dependencies>
 24             <!-- 核心包 -->
 25             <dependency>
 26                 <groupId>org.springframework</groupId>
 27                 <artifactId>spring-core</artifactId>
 28                 <version>${spring.version}</version>
 29             </dependency>
 30 
 31             <!-- pring IOC的基础实现,包含访问配置文件、创建和管理bean等 -->
 32             <dependency>
 33                 <groupId>org.springframework</groupId>
 34                 <artifactId>spring-beans</artifactId>
 35                 <version>${spring.version}</version>
 36             </dependency>
 37 
 38             <dependency>
 39                 <groupId>org.springframework</groupId>
 40                 <artifactId>spring-context</artifactId>
 41                 <version>${spring.version}</version>
 42             </dependency>
 43 
 44             <dependency>
 45                 <groupId>org.springframework</groupId>
 46                 <artifactId>spring-context-support</artifactId>
 47                 <version>${spring.version}</version>
 48             </dependency>
 49 
 50             <dependency>
 51                 <groupId>org.springframework</groupId>
 52                 <artifactId>spring-web</artifactId>
 53                 <version>${spring.version}</version>
 54             </dependency>
 55 
 56             <dependency>
 57                 <groupId>org.springframework</groupId>
 58                 <artifactId>spring-webmvc</artifactId>
 59                 <version>${spring.version}</version>
 60             </dependency>
 61 
 62             <dependency>
 63                 <groupId>org.springframework</groupId>
 64                 <artifactId>spring-tx</artifactId>
 65                 <version>${spring.version}</version>
 66             </dependency>
 67 
 68             <dependency>
 69                 <groupId>org.springframework</groupId>
 70                 <artifactId>spring-aop</artifactId>
 71                 <version>${spring.version}</version>
 72             </dependency>
 73 
 74 
 75             <dependency>
 76                 <groupId>org.springframework</groupId>
 77                 <artifactId>spring-aspects</artifactId>
 78                 <version>${spring.version}</version>
 79             </dependency>
 80 
 81             <dependency>
 82                 <groupId>org.springframework</groupId>
 83                 <artifactId>spring-jdbc</artifactId>
 84                 <version>${spring.version}</version>
 85             </dependency>
 86 
 87             <dependency>
 88                 <groupId>org.springframework</groupId>
 89                 <artifactId>spring-test</artifactId>
 90                 <version>${spring.version}</version>
 91             </dependency>
 92         </dependencies>
 93     </dependencyManagement>
 94 
 95     <!-- 依赖管理 -->
 96     <dependencies>
 97         <!-- spring相关包 -->
 98         <!-- 核心包 -->
 99         <dependency>
100             <groupId>org.springframework</groupId>
101             <artifactId>spring-core</artifactId>
102         </dependency>
103 
104         <!-- pring IOC的基础实现,包含访问配置文件、创建和管理bean等 -->
105         <dependency>
106             <groupId>org.springframework</groupId>
107             <artifactId>spring-beans</artifactId>
108         </dependency>
109 
110         <dependency>
111             <groupId>org.springframework</groupId>
112             <artifactId>spring-context</artifactId>
113         </dependency>
114 
115         <dependency>
116             <groupId>org.springframework</groupId>
117             <artifactId>spring-context-support</artifactId>
118         </dependency>
119 
120         <dependency>
121             <groupId>org.springframework</groupId>
122             <artifactId>spring-web</artifactId>
123         </dependency>
124 
125         <dependency>
126             <groupId>org.springframework</groupId>
127             <artifactId>spring-webmvc</artifactId>
128         </dependency>
129 
130         <dependency>
131             <groupId>org.springframework</groupId>
132             <artifactId>spring-tx</artifactId>
133         </dependency>
134 
135         <dependency>
136             <groupId>org.springframework</groupId>
137             <artifactId>spring-aop</artifactId>
138         </dependency>
139 
140 
141         <dependency>
142             <groupId>org.springframework</groupId>
143             <artifactId>spring-aspects</artifactId>
144         </dependency>
145 
146         <dependency>
147             <groupId>org.springframework</groupId>
148             <artifactId>spring-jdbc</artifactId>
149         </dependency>
150 
151         <dependency>
152             <groupId>org.springframework</groupId>
153             <artifactId>spring-test</artifactId>
154         </dependency>
155 
156         <!-- 数据库驱动 -->
157         <dependency>
158             <groupId>mysql</groupId>
159             <artifactId>mysql-connector-java</artifactId>
160             <version>5.1.6</version>
161             <scope>runtime</scope>
162         </dependency>
163 
164         <!-- c3p0 -->
165         <dependency>
166             <groupId>c3p0</groupId>
167             <artifactId>c3p0</artifactId>
168             <version>0.9.1.2</version>
169         </dependency>
170 
171         <!-- junit,4.12支持注解测试 -->
172         <dependency>
173             <groupId>junit</groupId>
174             <artifactId>junit</artifactId>
175             <version>4.12</version>
176             <scope>test</scope>
177         </dependency>
178 
179         <!-- aop联盟 -->
180         <dependency>
181             <groupId>org.aopalliance</groupId>
182             <artifactId>com.springsource.org.aopalliance</artifactId>
183             <version>1.0.0</version>
184         </dependency>
185 
186         <!-- weaver织入包 -->
187         <dependency>
188             <groupId>org.aspectj</groupId>
189             <artifactId>com.springsource.org.aspectj.weaver</artifactId>
190             <version>1.6.4.RELEASE</version>
191         </dependency>
192 
193     </dependencies>
194 </project>
pom.xml

相应的连接池和配置文件

  1. #加jdbc前缀的目的是为了避免后面的名字与其他地方名字冲突  
  2. jdbc.driver=com.mysql.jdbc.Driver  
  3. jdbc.url=jdbc:mysql://localhost:3306/数据库?characterEncoding=utf-8  
  4. jdbc.username=账号 
  5. jdbc.password=密码 
技术分享图片
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!-- 头部约束的作用:beans:最基本;context:读取资源文件;aop:配置aop;tx:配置事务通知 -->
 3 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns="http://www.springframework.org/schema/beans"
 5        xmlns:context="http://www.springframework.org/schema/context"
 6        xmlns:aop="http://www.springframework.org/schema/aop"
 7        xmlns:tx="http://www.springframework.org/schema/tx"
 8        xsi:schemaLocation="http://www.springframework.org/schema/beans
 9        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
10        http://www.springframework.org/schema/context
11        http://www.springframework.org/schema/context/spring-context-4.2.xsd
12        http://www.springframework.org/schema/aop
13        http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
14        http://www.springframework.org/schema/tx
15        http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
16 
17     <!-- 读取连接池配置文件 -->
18     <context:property-placeholder location="jdbc.properties"/>
19 
20     <!-- 1.将连接池放入spring容器 -->
21     <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
22         <!-- set注入 -->
23         <!--<property name="driverClass" value="com.mysql.jdbc.Driver"/>
24         <property name="jdbcUrl" value="jdbc:mysql:///test"/>
25         <property name="user" value="root"/>
26         <property name="password" value="admins"/>-->
27 
28         <!-- 资源文件配置 -->
29         <property name="driverClass" value="${jdbc.driver}"/>
30         <property name="jdbcUrl" value="${jdbc.url}"/>
31         <property name="user" value="${jdbc.username}"/>
32         <property name="password" value="${jdbc.password}"/>
33     </bean>
34 
35     <!-- 2.将JdbcTemplate放入spring容器 -->
36     <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
37         <property name="dataSource" ref="dataSource"/>
38     </bean>
39 
40     <!-- 3.将UserDao放入spring容器 -->
41     <bean name="userDao" class="com.dao.UserDaoImpl">
42         <property name="jt" ref="jdbcTemplate"/>
43     </bean>
44 
45     <!-- 无需依赖JdbcTemplate -->
46     <!-- 2.AccountDao放入spring容器 -->
47     <bean name="accountDao" class="com.dao.AccountDaoImpl">
48         <property name="dataSource" ref="dataSource"/>
49     </bean>
50 
51     <!-- 3.AccountService放入spring容器 -->
52     <bean name="accountService" class="com.service.AccountServiceImpl">
53         <property name="dao" ref="accountDao"/>
54         <property name="template" ref="transactionTemplate"/>
55     </bean>
56 
57     <!-- 3种事务管理方式 -->
58     <!-- 事务核心管理器,封装了事务的所有操作,依赖连接池 -->
59     <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
60         <!-- 依赖注入 -->
61         <property name="dataSource" ref="dataSource"/>
62     </bean>
63 
64     <!-- 1:编码方式;事务模板对象 -->
65     <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
66         <property name="transactionManager" ref="transactionManager"/>
67     </bean>
68 
69     <!-- 2:xml配置;配置事务通知 -->
70     <tx:advice transaction-manager="transactionManager" id="txAdvice">
71         <tx:attributes>
72             <!-- isolation:隔离级别;propagation:传播行为 ;read-only:只读-->
73             <!-- 以方法名为单位进行配置 -->
74             <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
75             <!-- 通常都会加通配符进行配置 -->
76             <tx:method name="save*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
77             <tx:method name="persist*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
78             <tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
79             <tx:method name="modify*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
80             <tx:method name="delete*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
81             <tx:method name="remove*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" />
82             <tx:method name="get*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
83             <tx:method name="find*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true" />
84         </tx:attributes>
85     </tx:advice>
86 
87     <!-- 配置织入 -->
88     <aop:config>
89         <!-- 目标对象 -->
90         <aop:pointcut id="txPc" expression="execution(* com.service.*ServiceImpl.*(..))"/>
91         <!-- 配置切面;advice-ref:通知;pointcut-ref:切入点 -->
92         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
93     </aop:config>
94 
95     <!-- 开启使用注解管理aop事务 -->
96     <tx:annotation-driven/>
97 </beans>
Sping配置文件

数据库不提供了,先来个bean

技术分享图片
 1 package com.bean;
 2 
 3 /**
 4  * @author: 肖德子裕
 5  * @date: 2018/9/9 14:55
 6  * @description: 实体bean
 7  */
 8 public class User {
 9     private int id;
10     private String name;
11 
12     public int getId() {
13         return id;
14     }
15 
16     public void setId(int id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     @Override
29     public String toString() {
30         return "User{" +
31                 "id=" + id +
32                 ", name=‘" + name + ‘\‘‘ +
33                 ‘}‘;
34     }
35 }
User

测试jdbc模板

技术分享图片
 1 package com.dao;
 2 
 3 import com.bean.User;
 4 
 5 import java.util.List;
 6 
 7 /**
 8  * @author: 肖德子裕
 9  * @date: 2018/9/9 14:56
10  * @description: 操作user接口
11  */
12 public interface UserDao {
13     //
14     void save(User user);
15     //根据用户ID删除
16     void delUserById(Integer id);
17     //
18     void update(User user);
19     //根据用户ID查询
20     User findUserById(Integer id);
21     //查询用户数量
22     int findCount();
23     //查询所有用户
24     List<User> findUserList();
25 }
UserDao
技术分享图片
 1 package com.dao;
 2 
 3 import com.bean.User;
 4 import org.springframework.jdbc.core.JdbcTemplate;
 5 import org.springframework.jdbc.core.RowMapper;
 6 
 7 import java.sql.ResultSet;
 8 import java.sql.SQLException;
 9 import java.util.List;
10 
11 /**
12  * @author: 肖德子裕
13  * @date: 2018/9/9 15:02
14  * @description: 使用jdbc模板实现增删改查
15  */
16 public class UserDaoImpl implements UserDao{
17     private JdbcTemplate jt;
18 
19     public void setJt(JdbcTemplate jt) {
20         this.jt = jt;
21     }
22 
23     @Override
24     public void save(User user) {
25         String sql="insert into user_info values(0,?)";
26         jt.update(sql,user.getName());
27     }
28 
29     @Override
30     public void delUserById(Integer id) {
31         String sql="delete from user_info where id=?";
32         jt.update(sql,id);
33     }
34 
35     @Override
36     public void update(User user) {
37         String sql="update user_info set name=? where id=?";
38         jt.update(sql,user.getName(),user.getId());
39     }
40 
41     @Override
42     public User findUserById(Integer id) {
43         String sql="select * from user_info where id=?";
44         return jt.queryForObject(sql, new RowMapper<User>() {//匿名内部类
45             //ResultSet:结果集;int i:第几行,即第几个数据
46             @Override
47             public User mapRow(ResultSet rs, int i) throws SQLException {
48                 User user=new User();
49                 user.setId(rs.getInt("id"));
50                 user.setName(rs.getString("name"));
51                 return user;
52             }
53         }, id);
54     }
55 
56     @Override
57     public int findCount() {
58         String sql="select count(*) from user_info";
59         Integer count=jt.queryForObject(sql,Integer.class);
60         return count;
61     }
62 
63     @Override
64     public List<User> findUserList() {
65         String sql="select * from user_info";
66         List<User> list=jt.query(sql, new RowMapper<User>() {
67             @Override
68             public User mapRow(ResultSet rs, int i) throws SQLException {
69                 User user=new User();
70                 user.setId(rs.getInt("id"));
71                 user.setName(rs.getString("name"));
72                 return user;
73             }
74         });
75         return list;
76     }
77 }
接口实现类
技术分享图片
 1 package com.jabcDemo;
 2 
 3 import com.bean.User;
 4 import com.dao.UserDao;
 5 import com.mchange.v2.c3p0.ComboPooledDataSource;
 6 import org.junit.Test;
 7 import org.junit.runner.RunWith;
 8 import org.springframework.jdbc.core.JdbcTemplate;
 9 import org.springframework.test.context.ContextConfiguration;
10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
11 
12 import javax.annotation.Resource;
13 
14 /**
15  * @author: 肖德子裕
16  * @date: 2018/9/9 13:50
17  * @description: 演示jdbc模板
18  */
19 @RunWith(SpringJUnit4ClassRunner.class)
20 @ContextConfiguration("classpath:applicationContext.xml")
21 public class Demo {
22     @Resource(name = "userDao")
23     private UserDao userDao;
24 
25     @Test
26     public void test() throws Exception{
27         //准备连接池
28         ComboPooledDataSource dataSource=new ComboPooledDataSource();
29         dataSource.setDriverClass("com.mysql.jdbc.Driver");
30         dataSource.setJdbcUrl("jdbc:mysql:///test");
31         dataSource.setUser("root");
32         dataSource.setPassword("admins");
33 
34         //创建jdbc模板对象
35         JdbcTemplate jt=new JdbcTemplate();
36         jt.setDataSource(dataSource);
37 
38         //书写sql,并执行
39         String sql="insert into user_info values(0,‘day‘)";
40         jt.update(sql);
41     }
42 
43     @Test
44     public void test1() throws Exception{
45         User user=new User();
46         user.setName("tom");
47         userDao.save(user);
48     }
49     @Test
50     public void test2() throws Exception{
51         User u = new User();
52         u.setId(2);
53         u.setName("jack");
54         userDao.update(u);
55 
56     }
57 
58     @Test
59     public void fun4() throws Exception{
60         userDao.delUserById(2);
61     }
62 
63     @Test
64     public void fun5() throws Exception{
65         System.out.println(userDao.findCount());
66     }
67 
68     @Test
69     public void fun6() throws Exception{
70         System.out.println(userDao.findUserById(1));
71     }
72 
73     @Test
74     public void fun7() throws Exception{
75         System.out.println(userDao.findUserList());
76     }
77 }
测试

测试事务管理方式

技术分享图片
 1 package com.dao;
 2 
 3 /**
 4  * @author: 肖德子裕
 5  * @date: 2018/9/9 16:54
 6  * @description: 事务的操作
 7  */
 8 public interface AccountDao {
 9     //加钱
10     void increaseMoney(Integer id,double money);
11     //减钱
12     void decreaseMoney(Integer id,double money);
13 }
AccountDao
技术分享图片
 1 package com.dao;
 2 
 3 import org.springframework.jdbc.core.support.JdbcDaoSupport;
 4 
 5 /**
 6  * @author: 肖德子裕
 7  * @date: 2018/9/9 16:57
 8  * @description: 不用jdbc模板,扩展知识(继承JdbcDaoSupport直接依赖连接池就行)
 9  */
10 public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{
11     @Override
12     public void increaseMoney(Integer id, double money) {
13         getJdbcTemplate().update("update t_acount set money=money+? where id=?",money,id);
14     }
15 
16     @Override
17     public void decreaseMoney(Integer id, double money) {
18         getJdbcTemplate().update("update t_acount set money=money-? where id=?",money,id);
19     }
20 }
接口实现类
技术分享图片
 1 package com.service;
 2 
 3 /**
 4  * @author: 肖德子裕
 5  * @date: 2018/9/9 17:03
 6  * @description: 逻辑运算
 7  */
 8 public interface AccountService {
 9     //转账方法
10     void transfer(Integer from,Integer to,double money);
11 }
AccountService
技术分享图片
 1 package com.service;
 2 
 3 import com.dao.AccountDao;
 4 import org.springframework.transaction.TransactionStatus;
 5 import org.springframework.transaction.annotation.Isolation;
 6 import org.springframework.transaction.annotation.Propagation;
 7 import org.springframework.transaction.annotation.Transactional;
 8 import org.springframework.transaction.support.TransactionCallbackWithoutResult;
 9 import org.springframework.transaction.support.TransactionTemplate;
10 
11 /**
12  * @author: 肖德子裕
13  * @date: 2018/9/9 17:06
14  * @description:
15  * 注解也可以加在类上;个别情况个别写
16  */
17 @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,readOnly = true)
18 public class AccountServiceImpl implements AccountService{
19     private AccountDao dao;
20     //事务模板
21     private TransactionTemplate template;
22 
23     public void setDao(AccountDao dao) {
24         this.dao = dao;
25     }
26 
27     public void setTemplate(TransactionTemplate template) {
28         this.template = template;
29     }
30 
31     //转账操作;匿名内部类要访问外部数据要加final
32     //事务模板已经封装好,只需提供操作
33     //模板过程(1.打开事务 2.调用doInTransactionWithoutResult方法 3.提交事务)
34     /*@Override
35     public void transfer(final Integer from,final Integer to,final double money) {
36         //根据不同的模板调用相应的接口
37         //不同的框架对事务的操作是不同的,但是事务的操作流程是一样的;所以spring提供接口来管理事务
38         template.execute(new TransactionCallbackWithoutResult() {
39             //实现对事务的管理
40             @Override
41             protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
42                 //减钱
43                 dao.decreaseMoney(from,money);
44                 //制造异常,测试事务是否有效;就是出现异常还会不会转钱
45                 //int i=1/0;
46                 //加钱
47                 dao.increaseMoney(to,money);
48             }
49         });
50     }*/
51 
52     //xml方式管理事务
53     //注解方式管理事务
54     @Override
55     @Transactional(isolation = Isolation.REPEATABLE_READ,propagation = Propagation.REQUIRED,readOnly = false)
56     public void transfer(Integer from, Integer to, double money) {
57         //减钱
58         dao.decreaseMoney(from,money);
59         //制造异常,测试事务是否有效;就是出现异常还会不会转钱
60         //int i=1/0;
61         //加钱
62         dao.increaseMoney(to,money);
63     }
64 }
接口实现类
技术分享图片
 1 package com.jabcDemo;
 2 
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4 import com.service.AccountService;
 5 import org.junit.Test;
 6 import org.junit.runner.RunWith;
 7 import org.springframework.jdbc.core.JdbcTemplate;
 8 import org.springframework.test.context.ContextConfiguration;
 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
10 
11 import javax.annotation.Resource;
12 
13 /**
14  * @author: 肖德子裕
15  * @date: 2018/9/9 13:50
16  * @description: 事务的操作
17  */
18 @RunWith(SpringJUnit4ClassRunner.class)
19 @ContextConfiguration("classpath:applicationContext.xml")
20 public class Demo2 {
21     @Resource(name = "accountService")
22     private AccountService as;
23 
24     @Test
25     public void test(){
26         //1给2转账500元
27         as.transfer(1,2,500d);
28     }
29 }
测试

 

Spring框架进阶3

标签:list   err   流程   oca   min   实体   poi   准备   color   

原文地址:https://www.cnblogs.com/xdzy/p/9617349.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!