spring boot 學習(五)SpringBoot+MyBatis(XML)+Druid


SpringBoot+MyBatis(xml)+Druid

前言

springboot集成了springJDBC與JPA,但是沒有集成mybatis,所以想要使用mybatis就要自己去集成。
主要是在Spring Boot中集成MyBatis,可以選用基於注解的方式,也可以選擇xml文件配置的方式。官方推薦使用xml文件配置。

springboot+mybatis+druid

1. 引入依賴

     <!-- Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
            <!-- 請不要使用1.0.0版本,因為還不支持攔截器插件 -->
        </dependency>
        <!-- druid阿里巴巴數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.20</version>
        </dependency>
        <!-- MySql數據庫驅動 -->
        <dependency>
            <groupId> mysql</groupId>
            <artifactId> mysql-connector-java</artifactId>
            <version> 5.0.5</version>
        </dependency>

 

2. 在Mysql中創建Users表

Users表中包含id(BIGINT)、name(INT)、age(VARCHAR)字段。

3. 創建接口Mapper(不是類)和對應的XML文件

User實體類:

public class User {

    private long id;
    private String name;
    private Integer age;

    // 省略相應的 getter 與 setter 方法
}

 UserDao接口:實現插入和查詢操作
注意必須加上@Mapper的注解,不然@Autowired將注入失敗。

@Mapper
public interface UserDao{

    int insertUser(@Param("user") User user);

    User findByName(String name);
}

 @Mapper注解標記這個接口作為一個映射接口。真正實現映射的方法(XML文件)需要源對象作為參數,並返回目標對象。
UserMapper.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="qg.fangrui.boot.dao.UserDao">
    <!--目的:為Dao接口方法提供SQL語句-->

    <!--映射實體對象-->
    <resultMap id="UserResultMap" type="qg.fangrui.boot.model.User">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
    </resultMap>

    <insert id="insertUser" >
        INSERT INTO users(name, age)
        VALUES (#{user.name}, #{user.age})
    </insert>

    <select id="findByName" resultType="User">
        SELECT * FROM users WHERE name = #{name}
    </select>

</mapper>

 

4. 配置文件

application.properties:

# 驅動配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/myboot?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver

#連接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=qg.fangrui.boot.model

 

5. 調用測試:

一般情況下,我是用Controller層調用Service層,Service層調用Dao層。測試案例比較簡單,我就不列了,只是簡單展示一下相應的Controller。

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private UserService userService;

    @RequestMapping("/add")
    public String add(User user){
        return String.valueOf(userService.add(user));
    }

}

 效果圖:
Postman測試圖:

Druid監控圖:

附錄

補充

mybatis-spring-boot-starter的依賴樹:
依賴樹

Mybatis 在 SpringBoot 中的配置:
* mybatis.mapper-locations:xml文件掃描位置
* mybatis.type-aliases-package:Model包掃描位置
* mybatis.config:mybatis-config.xml配置文件的路徑
* mybatis.typeHandlersPackage:掃描typeHandlers的包
* mybatis.checkConfigLocation:檢查配置文件是否存在
* mybatis.executorType:設置執行模式(SIMPLE, REUSE, BATCH),默認為SIMPLE

項目參考

集合了我的 SpringBoot 學習的案例:
包括了我前面學習的案例!
SpringBoot+MyBatis+Druid

參考資料

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM