SpringBoot 整合 Mybatis

SpringBoot Mybatis 整合

SpringBoot Mybatis这么有名的框架,不多解释了他俩了,本文采用最基础的方式整合mybatis,大家可以再整合mybatis puls或tkmybatis

废话不多说了,直接开始

1.环境/版本一览:

  • 开发工具:Intellij IDEA 2020.2.3
  • springboot:2.3.7.RELEASE
  • jdk:1.8.0_211
  • maven: 3.6.3

2.工程结构:

3.开始搭建:

  • 创建数据库 t_user_db
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `pwd` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sys_user
-- ----------------------------
BEGIN;
INSERT INTO `sys_user` VALUES (1, 'test', '123');
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;
  • 新建项目

  • pom.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.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.niu</groupId>
    <artifactId>datasource</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>datasource</name>
    <description>Demo project for Spring Boot</description>

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

    <dependencies>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  • 创建配置文件 application.yml
server:
  port: 8080

spring:
  datasource:
    name: main_db
    type: com.alibaba.druid.pool.DruidDataSource
    #druid相关配置
    druid:
      #监控统计拦截的filters
      filters: stat
      driver-class-name: com.mysql.jdbc.Driver
      #基本属性
      url: jdbc:mysql://127.0.0.1:3306/t_user_db?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
      username: root
      password: Abcdef@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

mybatis:
  mapper-locations: classpath:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.niu.datasource.model  # 注意:对应实体类的路径
  • 创建model
public class SysUser {
    private Integer id;
    private String name;
    private String pwd;

       //get/set省略,记得加上
}
  • 创建mapper
@Repository
public interface SysUserMapper {

    SysUser selectUserById(Integer id);
}
  • 创建service
@Service
public class UserService {

    @Autowired
    private SysUserMapper userMapper;

    public SysUser getUser(Integer id){
        return  userMapper.selectUserById(id);
    }


}
  • 创建controller 这里我们让接口都返回json 使用@RestController注解
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{userId}")
    public SysUser user(@PathVariable  Integer userId){
        return userService.getUser(userId);
    }
}
  • 在resources新建mapper文件夹并创建SysUserMapper.xml文件  注意包名,要和自己的一致
<?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.niu.springboot.mapper.SysUserMapper" >
    <sql id="BASE_TABLE">
    sys_user
   </sql>

    <sql id="BASE_COLUMN">
    id,name,pwd
  </sql>



    <select id="selectUserById" resultType="com.niu.springboot.model.SysUser">
        SELECT
        <include refid="BASE_COLUMN"/>
        FROM
        <include refid="BASE_TABLE"/>
        <where>
            id = #{id}
        </where>
    </select>


</mapper>
  • 主类  注意@MapperScan包名,要和自己的一致
@SpringBootApplication
@MapperScan("com.niu.springboot.mapper") //mapper接口所在的包路径
public class SpringbootMybatisApplication {

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

}

4.启动测试

大功告成

代码已经推送至github:https://github.com/NiuXiangQian/springboot-mybatis/

正文到此结束
评论插件初始化中...
Loading...