springboot集成mybatis后实现事务管理

    JavaWeb开发中现在基本上都是采用springboot开发。自己在学习springboot中进行个小练习。公司项目
都是采用mybatisplus进行开发的。此次练习也为了让自己对springboot集合mybatis再次温故一下。期间果真
出现了不少问题(多加练习)。记录下来学习的过程。上代码!

POM.xml(推荐加上检测xml的依赖)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml
                
                true
            
        
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



yml文件(自己练习时也要写两个,通过主去引用dev)

server:
  port: 8888
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations:
    - classpath:mapping/*.xml

SQL语句

CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `userName` varchar(32) NOT NULL,
  `passWord` varchar(50) NOT NULL,
  `realName` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

实体类

package cn.zxw.bean;

import lombok.Data;

/**
 * @author zxw
 * @version 1.0
 * @description 用户
 * @data: 2020/2/16 14:37
 */
@Data
public class User {

    private Integer id;

    private String username;
    private String password;
    private String realName;

}

service

package cn.zxw.service;

import cn.zxw.bean.User;

/**
 * @author zxw
 * @version 1.0
 * @description 持久层接口
 * @data: 2020/2/16 14:38
 */
public interface UserService {
    /**
     * 保存用户
     * @param user 用户
     */
    void saveUser(User user);

    /**
     * 获取用户
     * @param id
     * @return
     */
    User getUserById(Integer id);

    /**
     * 根据id更改名字
     * @param id
     * @param name
     * @return
     */
    int updateUserById(Integer id, String name);
}

实体类

package cn.zxw.service.impl;

import cn.zxw.bean.User;
import cn.zxw.mapper.UserDao;
import cn.zxw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zxw
 * @version 1.0
 * @description 业务层实现类
 * @data: 2020/2/16 14:39
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public void saveUser(User user) {
        userDao.save(user);
    }

    @Override
    public User getUserById(Integer id) {
        return userDao.getUserById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)//通过添加注解或去除注解来看是否生效
    public int updateUserById(Integer id, String name) {
        int i = userDao.updateUserById(id, name);
        //制造异常
        int a = 1 / 0;
        return i;
    }
}

dao接口(可以使用xml或者注解两种)

package cn.zxw.mapper;

import cn.zxw.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

/**
 * @author zxw
 * @version 1.0
 * @description dao
 * @data: 2020/2/16 15:08
 */
@Mapper
public interface UserDao {
    /**
     * 保存用户
     * @param user
     */
    void save(@Param("user") User user);

    /**
     * 获取
     * @param id
     * @return
     */
    User getUserById(Integer id);

    /**
     * 更新用户
     * @param id
     * @param name
     * @return
     */
    @Update("update user set username = #{name} where id = #{id}")
    int updateUserById(@Param("id") Integer id,@Param("name") String name);
}

controller

package cn.zxw.controller;

import cn.zxw.bean.User;
import cn.zxw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zxw
 * @version 1.0
 * @description 用户
 * @data: 2020/2/16 15:48
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/getUserById")
    public User getUserById(Integer id) {
        return userService.getUserById(id);
    }

    @PostMapping("/updateUserById")
    public String updateUserById(Integer id, String name) {
        int flag = userService.updateUserById(id, name);
        if (flag < 1){
            return "false";
        }
        return "success";
    }
}

启动类(别忘了添加上EnableTransactionManagement注解)

package cn.zxw;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author zxw
 */
@SpringBootApplication
@EnableTransactionManagement
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

你可能感兴趣的:(学习路上)