SpringBoot 简单整合 Druid + Mybatis 例子

DB:MYSQL

jdk:1.8

SpringBoot 版本 2.0.5.RELEASE

Druid: 这里用的是druid-spring-boot-starter 1.1.10

Mybatis : 这里用的是 mybatis-spring-boot-starter 1.3.2

1. 生成Spring boot demo

先通过Spring 的官网 https://start.spring.io/ 来生成一个SpringBoot的demo

2..xml添加依赖

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>            

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.8</version>
        </dependency>

3.配置属性文件application.yml,druid参数配置可以参考文档

https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

https://github.com/alibaba/druid

spring:
  datasource:
    name: test
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&autoReconnect=true&useSSL=false&useAffectedRows=true
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    druid:
      #初始化、最小、最大连接数
      initial-size: 5
      min-idle: 5
      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的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置监控统计拦截的filters
      filters: stat
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# mybatis_config
mybatis:
  mapper-locations: classpath:com/XXXXXXXXXX/dao/mapper/*.xml

4.添加完druid的配置,启动项目可以直接访问druid监控页面,http://localhost:8080/druid/index.html

5.创建Mybatis的Mapper、pojo,以及测试controller等

1)Mapper接口

@Mapper
@Component(value="userMapper")
public interface UserMapper {
    public User selectByPrimaryKey(Integer id);
}

2)Java Bean对象

@Data
public class User {

    private Integer id;

    private String name;
}

3)Mapper.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.XXXX.XXXXXX.dao.mapper.UserMapper">
    <resultMap id="baseMap" type="com.XXXX.XXXXXX.dao.pojo.User">
        <id column="id" property="id" jdbcType="INTEGER"></id>
        <result column="name" property="name" jdbcType="VARCHAR"></result>
    </resultMap>
    
    <sql id="base_column_list">
        id,name
    </sql>

    <select id="selectByPrimaryKey" resultMap="baseMap" parameterType="Integer">
        select
          <include refid="base_column_list"/>
        from user
        where id = #{id}
    </select>
</mapper>

以上的内容可以通过Mybatis Generator来自动生成,从而减少手写的错误

4)Service

public interface UserService {
    User selectByPrimaryKey(Integer id);
}
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

}

5)Controller

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/user/{id}")
    public User selectByPrimaryKey(@PathVariable int id){
        return  userService.selectByPrimaryKey(id);
    }
}

6)Application上添加@MapperScan注解

@SpringBootApplication
@MapperScan("com.XXXX.XXXXXX.dao.mapper")
public class TestApplication {
   public static void main(String[] args) {
      SpringApplication.run(TestApplication.class, args);
   }
}
6.测试Controller是否能正常运行
{"id":1,"name":"测试1"}

浏览器打印出测试结果,因为查询成功,整个流程就通了。

SQL语句的执行情况,可以再Druid的SQL监控页面查看到。

猜你喜欢

转载自my.oschina.net/u/2329222/blog/2254632