SpringBoot Mybatis 整合(完整版)

转载文章:https://blog.csdn.net/Winter_chen001/article/details/77249029

正题

本项目使用的环境:

  • 开发工具:Intellij IDEA 2017.1.3
  • springboot: 2.2.1
  • jdk:1.8.0_161
    -maven:3.3.9

额外功能

  • PageHelper 分页插件
  • mybatis generator 自动生成代码插件

步骤:

1.创建一个springboot项目:

2.创建项目的文件结构以及jdk的版本

3.选择项目所需要的依赖


然后点击finish

5.看一下文件的结构:

image.png

6.查看一下pom.xml:



    4.0.0

    com.winter
    springboot-mybatis-demo
    0.0.1-SNAPSHOT
    jar

    springboot-mybatis-demo
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.1.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.7
    

    
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.0
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            mysql
            mysql-connector-java
            5.1.35
        
        
    
        
            com.fasterxml.jackson.core
            jackson-core
        
        
            com.fasterxml.jackson.core
            jackson-databind
        
        
            com.fasterxml.jackson.datatype
            jackson-datatype-joda
        
        
            com.fasterxml.jackson.module
            jackson-module-parameter-names
        

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

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.0
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.2
                
                    ${basedir}/src/main/resources/generator/generatorConfig.xml
                    true
                    true
                
            
        
    



7.项目不使用application.properties文件 而使用更加简洁的application.yml文件,将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,文件的内容如下:


server:
  port: 8080

spring:
    datasource:
        name: test
        url: jdbc:mysql://127.0.0.1:3306/depot
        username: root
        password: root
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
  mapper-locations: classpath:mapping/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.winter.model  # 注意:对应实体类的路径

#pagehelper分页插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

8.创建数据库:

CREATE DATABASE mytest;

CREATE TABLE t_user(
  user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  user_name VARCHAR(255) NOT NULL ,
  password VARCHAR(255) NOT NULL ,
  phone VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;

9.使用mybatis generator 自动生成代码:

  • 配置pom.xml中generator 插件所对应的配置文件${basedir}/src/main/resources/generator/generatorConfig.xml



    
    
    
        
            
            
            
        
        
        
        
        
            
        
        
        
            
            
        
        
        
            
        
        
        
            
        
        
        
  • 点击run-Edit Configurations
  • 添加配置

运行 : 注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记

最后生成的文件以及结构:

10. 生成的文件

UserMapper.java

package com.winter.mapper;

import com.winter.model.User;

public interface UserMapper {
    int deleteByPrimaryKey(Integer userId);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userId);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
    //这个方式我自己加的
    List selectAllUser();
}

User.java

package com.winter.model;

public class User {
    private Integer userId;

    private String userName;

    private String password;

    private String phone;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }
}

UserMapper.xml





  
    
    
    
    
  
  
    user_id, user_name, password, phone
  
  
  
  
  
    delete from t_user
    where user_id = #{userId,jdbcType=INTEGER}
  
  
    insert into t_user (user_id, user_name, password, 
      phone)
    values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{phone,jdbcType=VARCHAR})
  
  
    insert into t_user
    
      
        user_id,
      
      
        user_name,
      
      
        password,
      
      
        phone,
      
    
    
      
        #{userId,jdbcType=INTEGER},
      
      
        #{userName,jdbcType=VARCHAR},
      
      
        #{password,jdbcType=VARCHAR},
      
      
        #{phone,jdbcType=VARCHAR},
      
    
  
  
    update t_user
    
      
        user_name = #{userName,jdbcType=VARCHAR},
      
      
        password = #{password,jdbcType=VARCHAR},
      
      
        phone = #{phone,jdbcType=VARCHAR},
      
    
    where user_id = #{userId,jdbcType=INTEGER}
  
  
    update t_user
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR}
    where user_id = #{userId,jdbcType=INTEGER}
  


11.打开类SpringbootMybatisDemoApplication.java,这个是springboot的启动类。我们需要添加点东西:

package com.winter;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.winter.mapper")//将项目中对应的mapper类的路径加进来就可以了
public class SpringbootMybatisDemoApplication {

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

注意:@MapperScan("com.winter.mapper")这个注解非常的关键,这个对应了项目中mapper(dao)所对应的包路径,很多同学就是这里忘了加导致异常的

12.到这里所有的搭建工作都完成了,接下来就是测试的工作,没使用junit4进行测试:首先看一下完成之后的文件的结构:

现在controller,service层的代码都写好:

UserController.java

package com.winter.Controller;

import com.winter.model.User;
import com.winter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Administrator on 2017/8/16.
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ResponseBody
    @RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
    public int addUser(User user){
        return userService.addUser(user);
    }

    @ResponseBody
    @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})
    public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
        
        return userService.findAllUser(pageNum,pageSize);
    }
}

UserService.java

package com.winter.service;

import com.winter.model.User;

import java.util.List;

/**
 * Created by Administrator on 2017/8/16.
 */
public interface UserService {

    int addUser(User user);

    List findAllUser(int pageNum, int pageSize);
}

UserServiceImpl.java

package com.winter.service.impl;

import com.github.pagehelper.PageHelper;
import com.winter.mapper.UserMapper;
import com.winter.model.User;
import com.winter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by Administrator on 2017/8/16.
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService {

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

    @Override
    public int addUser(User user) {

        return userMapper.insertSelective(user);
    }

    /*
    * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
    * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
    @Override
    public List findAllUser(int pageNum, int pageSize) {
        //将参数传给这个方法就可以实现物理分页了,非常简单。
        PageHelper.startPage(pageNum, pageSize);
        return userMapper.selectAllUser();
    }
}

13. 点击运行:http://127.0.0.1:8080/user/all/2/10

你可能感兴趣的:(SpringBoot Mybatis 整合(完整版))