1. 程式人生 > >SpringBoot 簡單整合 Druid + Mybatis 例子

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監控頁面檢視到。