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

基于 spring boot + mybatis-plus实现简单的转账业务

时间:2017-08-08 17:48:17      阅读:5680      评论:0      收藏:0      [点我收藏+]

标签:tac   oba   plugins   utf8   sda   www.   简单   from   ica   

需求:aa向bb转账2000

1.准备工作

简单的数据库

技术分享

 

2.创建springboot项目,添加依赖pom.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5 
 6     <groupId>com</groupId>
 7     <artifactId>mybatisplus_demo3</artifactId>
 8     <version>0.0.1-SNAPSHOT</version>
 9     <packaging>jar</packaging>
10 
11     <name>mybatisplus_demo3</name>
12     <description>Demo project for Spring Boot</description>
13 
14     <parent>
15         <groupId>org.springframework.boot</groupId>
16         <artifactId>spring-boot-starter-parent</artifactId>
17         <version>1.5.6.RELEASE</version>
18         <relativePath /> <!-- lookup parent from repository -->
19     </parent>
20 
21     <properties>
22         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
23         <maven.compiler.source>1.7</maven.compiler.source>
24         <maven.compiler.target>1.7</maven.compiler.target>
25         <mybatisplus-spring-boot-starter.version>1.0.4</mybatisplus-spring-boot-starter.version>
26         <mybatisplus.version>2.1-gamma</mybatisplus.version>
27         <fastjson.version>1.2.31</fastjson.version>
28     </properties>
29 
30     <dependencies>
31         <dependency>
32             <groupId>org.springframework.boot</groupId>
33             <artifactId>spring-boot-starter-web</artifactId>
34         </dependency>
35         <dependency>
36             <groupId>org.springframework.boot</groupId>
37             <artifactId>spring-boot-starter-jetty</artifactId>
38         </dependency>
39         <dependency>
40             <groupId>com.h2database</groupId>
41             <artifactId>h2</artifactId>
42         </dependency>
43 
44         <!-- mybatis-plus begin -->
45         <dependency>
46             <groupId>org.springframework.boot</groupId>
47             <artifactId>spring-boot-starter-jdbc</artifactId>
48         </dependency>
49         <dependency>
50             <groupId>com.baomidou</groupId>
51             <artifactId>mybatisplus-spring-boot-starter</artifactId>
52             <version>${mybatisplus-spring-boot-starter.version}</version>
53         </dependency>
54         <dependency>
55             <groupId>com.baomidou</groupId>
56             <artifactId>mybatis-plus</artifactId>
57             <version>${mybatisplus.version}</version>
58         </dependency>
59         <!-- mybatis-plus end -->
60 
61         <!-- JUnit test dependency -->
62         <dependency>
63             <groupId>org.springframework.boot</groupId>
64             <artifactId>spring-boot-starter-test</artifactId>
65         </dependency>
66         <dependency>
67             <groupId>com.alibaba</groupId>
68             <artifactId>fastjson</artifactId>
69             <version>${fastjson.version}</version>
70         </dependency>
71         <dependency>
72             <groupId>mysql</groupId>
73             <artifactId>mysql-connector-java</artifactId>
74         </dependency>
75     </dependencies>
76 
77     <build>
78         <plugins>
79             <plugin>
80                 <groupId>org.springframework.boot</groupId>
81                 <artifactId>spring-boot-maven-plugin</artifactId>
82             </plugin>
83         </plugins>
84     </build>
85 </project>

3.使用官方提供的代码生成器,生成entity,controller,service,mapper类

  1 import java.util.ArrayList;
  2 import java.util.HashMap;
  3 import java.util.List;
  4 import java.util.Map;
  5 
  6 import com.baomidou.mybatisplus.generator.*;
  7 import com.baomidou.mybatisplus.generator.config.*;
  8 import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
  9 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 10 import com.baomidou.mybatisplus.generator.config.rules.*;
 11 
 12 /**
 13  * <p>
 14  * 代码生成器演示
 15  * </p>
 16  */
 17 public class MpGenerator {
 18 
 19     /**
 20      * <p>
 21      * MySQL 生成演示
 22      * </p>
 23      */
 24     public static void main(String[] args) {
 25         AutoGenerator mpg = new AutoGenerator();
 26 
 27         // 全局配置
 28         GlobalConfig gc = new GlobalConfig();
 29         gc.setOutputDir("D://mp_gen//");
 30         gc.setFileOverride(true);
 31         gc.setActiveRecord(true);
 32         gc.setEnableCache(false);// XML 二级缓存
 33         gc.setBaseResultMap(true);// XML ResultMap
 34         gc.setBaseColumnList(false);// XML columList
 35         gc.setAuthor("JIE");
 36 
 37         // 自定义文件命名,注意 %s 会自动填充表实体属性!
 38         // gc.setMapperName("%sDao");
 39         // gc.setXmlName("%sDao");
 40         // gc.setServiceName("MP%sService");
 41         // gc.setServiceImplName("%sServiceDiy");
 42         // gc.setControllerName("%sAction");
 43         mpg.setGlobalConfig(gc);
 44 
 45         // 数据源配置
 46         DataSourceConfig dsc = new DataSourceConfig();
 47         dsc.setDbType(DbType.MYSQL);
 48         
 49         dsc.setTypeConvert(new MySqlTypeConvert(){
 50             // 自定义数据库表字段类型转换【可选】
 51             @Override
 52             public DbColumnType processTypeConvert(String fieldType) {
 53                 System.out.println("转换类型:" + fieldType);
 54                 // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
 55                 return super.processTypeConvert(fieldType);
 56             }
 57         });
 58         dsc.setDriverName("com.mysql.jdbc.Driver");
 59         dsc.setUsername("root");
 60         dsc.setPassword("1234");
 61         dsc.setUrl("jdbc:mysql://127.0.0.1:3306/account_spring?characterEncoding=utf8");
 62         mpg.setDataSource(dsc);
 63 
 64         // 策略配置
 65         StrategyConfig strategy = new StrategyConfig();
 66     // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
 67         //strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
 68         strategy.setTablePrefix(new String[] { "account_spring" });// 此处可以修改为您的表前缀
 69         strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
 70         // strategy.setInclude(new String[] { "user" }); // 需要生成的表
 71         // strategy.setExclude(new String[]{"test"}); // 排除生成的表
 72         // 自定义实体父类
 73         // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");
 74         // 自定义实体,公共字段
 75         // strategy.setSuperEntityColumns(new String[] { "test_id", "age" });
 76         // 自定义 mapper 父类
 77         // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
 78         // 自定义 service 父类
 79         // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
 80         // 自定义 service 实现类父类
 81         // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
 82         // 自定义 controller 父类
 83         // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
 84         // 【实体】是否生成字段常量(默认 false)
 85         // public static final String ID = "test_id";
 86         // strategy.setEntityColumnConstant(true);
 87         // 【实体】是否为构建者模型(默认 false)
 88         // public User setName(String name) {this.name = name; return this;}
 89         // strategy.setEntityBuilderModel(true);
 90         mpg.setStrategy(strategy);
 91 
 92         // 包配置
 93         PackageConfig pc = new PackageConfig();
 94         pc.setParent("com");
 95         pc.setModuleName("mp");
 96         mpg.setPackageInfo(pc);
 97 
 98         // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
 99         InjectionConfig cfg = new InjectionConfig() {
100             @Override
101             public void initMap() {
102                 Map<String, Object> map = new HashMap<String, Object>();
103                 map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
104                 this.setMap(map);
105             }
106         };
107 
108         // 自定义 xxList.jsp 生成
109         List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
110 //        focList.add(new FileOutConfig("/templates/list.jsp.vm") {
111 //            @Override
112 //            public String outputFile(TableInfo tableInfo) {
113 //                // 自定义输入文件名称
114 //                return "D://my_" + tableInfo.getEntityName() + ".jsp";
115 //            }
116 //        });
117 //        cfg.setFileOutConfigList(focList);
118 //        mpg.setCfg(cfg);
119 
120         // 调整 xml 生成目录演示
121          focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
122             @Override
123             public String outputFile(TableInfo tableInfo) {
124                 return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
125             }
126         });
127         cfg.setFileOutConfigList(focList);
128         mpg.setCfg(cfg);
129 
130         // 关闭默认 xml 生成,调整生成 至 根目录
131         TemplateConfig tc = new TemplateConfig();
132         tc.setXml(null);
133         mpg.setTemplate(tc);
134 
135         // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
136         // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
137         // TemplateConfig tc = new TemplateConfig();
138         // tc.setController("...");
139         // tc.setEntity("...");
140         // tc.setMapper("...");
141         // tc.setXml("...");
142         // tc.setService("...");
143         // tc.setServiceImpl("...");
144     // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
145         // mpg.setTemplate(tc);
146 
147         // 执行生成
148         mpg.execute();
149 
150         // 打印注入设置【可无】
151         System.err.println(mpg.getCfg().getMap().get("abc"));
152     }
153 
154 }

添加至项目,结构如下

技术分享

4.src/main/resources下的资源配置

4.1 application.yml

 1 server:
 2   port: 8090
 3   
 4 #Spring配置数据源
 5 spring:
 6   devtools:
 7     restart:
 8       enabled: false
 9   datasource:
10     driver-class-name: com.mysql.jdbc.Driver 
11     url: jdbc:mysql://localhost:3306/account_spring
12     username: root
13     password: 1234 
14 
15 #MyBatis
16 mybatis-plus:
17   mapper-locations: classpath:mapper/TUserMapper.xml
18   type-aliases-package: com.mp.entity
19   global-config:
20     id-type: 2
21     field-strategy: 2
22      #驼峰下划线转换
23     db-column-underline: true
24     refresh-mapper: true
25   configuration:
26     map-underscore-to-camel-case: true
27     cache-enabled: false
28   #logging
29 logging:
30   level: warn
31   
32   

4.2 mapper/TUserMapper.xml(Mybatis映射文件)由于此项目所涉及的CURD mp都已经封装好

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mp.mapper.TUserMapper">
</mapper>

5.Controller层

 1 package com.mp.web;
 2 
 3 
 4 import org.springframework.web.bind.annotation.ExceptionHandler;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.ResponseBody;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 import com.baomidou.mybatisplus.mapper.EntityWrapper;
10 import com.baomidou.mybatisplus.mapper.Wrapper;
11 import com.baomidou.mybatisplus.plugins.Page;
12 import com.mp.entity.TUser;
13 import com.mp.service.ITUserService;
14 
15 import java.util.List;
16 
17 import org.springframework.beans.factory.annotation.Autowired;
18 import org.springframework.stereotype.Controller;
19 
20 /**
21  * <p>
22  *  前端控制器
23  * </p>
24  *
25  * @author JIE
26  * @since 2017-08-08
27  */
28 @RestController
29 @RequestMapping("/mp")
30 public class TUserController {
31     
32     @Autowired
33     private ITUserService tUserService;
34     
35     @RequestMapping("/transfer")
36     public String doTransfer() {
37         
38         String result = tUserService.transfer(1, 2, 2000d);
39         return result;
40     }
41     @ExceptionHandler({ Exception.class })
42     public String processException(Exception exception) {
43         return "failure";
44     }
45 }

 

6.service层

 1 package com.mp.service.impl;
 2 
 3 import com.mp.entity.TUser;
 4 import com.mp.mapper.TUserMapper;
 5 import com.mp.service.ITUserService;
 6 import com.baomidou.mybatisplus.mapper.EntityWrapper;
 7 import com.baomidou.mybatisplus.service.impl.ServiceImpl;
 8 import org.springframework.stereotype.Service;
 9 import org.springframework.transaction.annotation.Transactional;
10 
11 /**
12  * <p>
13  *  服务实现类
14  * </p>
15  *
16  * @author JIE
17  * @since 2017-08-08
18  */
19 @Service
20 public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {
21 
22     /**
23      * 转账业务
24      */
25     @Override
26     @Transactional
27     public String transfer(Integer from, Integer to, Double money) {
28         try {
29             //from减少money
30             TUser tUserFrom = baseMapper.selectById(from);
31             EntityWrapper<TUser> ew = new EntityWrapper<TUser>();
32             ew.where("id={0}", tUserFrom.getId());
33             tUserFrom.setMoney(tUserFrom.getMoney()-money);
34             baseMapper.update(tUserFrom, ew);
35             
36             int i = 1/0;    //异常
37             //to增加money
38             TUser tUserTo = baseMapper.selectById(to);
39             tUserTo.setMoney(tUserTo.getMoney()+money);
40             EntityWrapper<TUser> ew2 = new EntityWrapper<TUser>();
41             ew2.where("id={0}", tUserTo.getId());
42             baseMapper.update(tUserTo, ew2);
43             return "success";
44         } catch (Exception e) {
45             throw e;
46         }
47     }
48     
49 }

 

 

 

结果

(1)启动项目,在浏览器输入http://localhost:8090/mp/transfer

技术分享技术分享---转账成功

(2)把service中的异常放开 int i = 1 / 0 将 aa bb 的money 均修改为10000,启动项目

技术分享技术分享--转账失败,由于加入了事务管理,数据库数据不改变

参考官方项目:mybatisplus-spring-boot

基于 spring boot + mybatis-plus实现简单的转账业务

标签:tac   oba   plugins   utf8   sda   www.   简单   from   ica   

原文地址:http://www.cnblogs.com/cookwithme/p/7307882.html

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