springboot整合MyBatis及事务管理

本文使用xml版 Spring Boot整合MyBatis

目录

目录

1、依赖

2、application.yml

3、建表

4、实体类:User

5、UserDao

6、UserMapper.xml

7、UserService 

8、UserServiceImpl

9、UserController

10、用postman测试

 11、解决的bug

12、事务管理


1、依赖



	4.0.0
	
		org.springframework.boot
		spring-boot-starter-parent
		2.1.3.RELEASE
		 
	
	com.zj
	springboot-mybatis-annotation
	0.0.1-SNAPSHOT
	springboot-mybatis-annotation
	Demo project for Spring Boot

	
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-jdbc
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			2.0.0
		
		
			mysql
			mysql-connector-java
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.9
        

		
		
			com.github.pagehelper
			pagehelper-spring-boot-starter
			1.2.5
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

2、application.yml

server:
  port: 8080


spring:
    datasource:
        name: mysql_test
        type: com.alibaba.druid.pool.DruidDataSource
        #druid相关配置
        druid:
          #监控统计拦截的filters
          filters: stat
#          driver-class-name: com.mysql.jdbc.Driver
          driver-class-name: com.mysql.cj.jdbc.Driver
          #基本属性
          url: jdbc:mysql://127.0.0.1:3306/springboot_study?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8
          username: root
          password: 123456
          #配置初始化大小/最小/最大
          initial-size: 1
          min-idle: 1
          max-active: 20
          #获取连接等待超时时间
          max-wait: 60000
          #间隔多久进行一次检测,检测需要关闭的空闲连接
          time-between-eviction-runs-millis: 60000
          #一个连接在池中最小生存的时间
          min-evictable-idle-time-millis: 300000
          validation-query: SELECT 'x'
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
          #打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
          pool-prepared-statements: false
          max-pool-prepared-statement-per-connection-size: 20
## 该配置节点为独立的节点,有很多人容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
  mapper-locations: classpath:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.zj.springbootmybatisannotation.model  # 注意:对应实体类的路径

#pagehelper
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
    returnPageInfo: check

把数据库改成自己的

 

注意一下目录结构:

springboot整合MyBatis及事务管理_第1张图片

同时修改启动类: SpringbootMybatisAnnotationApplication 

@SpringBootApplication
@MapperScan("com.zj.springbootmybatisannotation.dao")
public class SpringbootMybatisAnnotationApplication {

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

}

注意:@MapperScan("com.zj.springbootmybatisannotation.dao")这个注解,这个对应了项目中mapper(dao)所对应的包路径,

3、建表

SET FOREIGN_KEY_CHECKS=0;



DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;


INSERT INTO `user` VALUES ('1', 'aaa', '18');
INSERT INTO `user` VALUES ('2', 'bbb', '18');
INSERT INTO `user` VALUES ('3', 'ccc', '20');
INSERT INTO `user` VALUES ('4', 'ddd', '24');
INSERT INTO `user` VALUES ('5', '111', null);

4、实体类:User

public class User {

    private Integer id;

    private String username;

    private Integer age;



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() { //重写toString() 方法,便于打印消息
        return String.format("User[id=%d, username='%s', age=%d]",
                id, username, age);
    }

5、UserDao

public interface UserDao {

    int insert(User record);


    List selectUsers();

}

6、UserMapper.xml




    
        user
    

    
        id,username,age
    

    
        INSERT INTO
        
        
            username,age
        
        
            #{username, jdbcType=VARCHAR},#{age, jdbcType=VARCHAR}
        
    

    



7、UserService 

public interface UserService {

    int addUser(User user);

    PageInfo findAllUser(int pageNum, int pageSize);

}

8、UserServiceImpl

@Service(value = "UserService")
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;//这里会报错,但是并不会影响

    @Override
    public int addUser(User user) {

        return userDao.insert(user);
    }

    @Override
    public PageInfo findAllUser(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了,非常简单。
        PageHelper.startPage(pageNum, pageSize);
        List userDomains = userDao.selectUsers();
        PageInfo result = new PageInfo(userDomains);
        return result;

    }
}

9、UserController

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public int addUser(User user){
        return userService.addUser(user);
    }

    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
                    int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                    int pageSize){
        return userService.findAllUser(pageNum,pageSize);
    }


}

10、用postman测试

springboot整合MyBatis及事务管理_第2张图片

springboot整合MyBatis及事务管理_第3张图片

 11、解决的bug

解决bug:

java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver 

https://blog.csdn.net/qq_15653601/article/details/79940090

12、事务管理

springboot 开启事物很简单,只需要加一行注解就可以了,前提你用的是jdbctemplate, jpa, mybatis,这种常见的orm。

 @GetMapping("/test")
    @Transactional
    public Object test1111111() throws Exception{
                User user = new User();
                user.setUsername( "xxxx" );
                user.setAge( 18 );
                userService.addUser( user );

                int i=1/0;

                User user1 = new User();
                user1.setUsername( "yyyy" );
                user1.setAge( 22 );
                userService.addUser( user1 );
                return "插入成功";
    }

当代码运行到第一个addUser时,数据库插入数据,但出现异常时,数据库回滚,数据库什么也没有插入。

你可能感兴趣的:(springboot,springboot)