从0开始SpringBoot - 3:SpringBoot + MyBatis+DBConnectionPool

133 阅读2分钟

SpringBoot + MyBatis + DB ConnectionPool (HiKariCP)

本地环境
  1. 安装本地mysql
  2. 安装个db ui tool,例如 Navicat for mysql
  3. 测试连接上db
  1. 配置 DataSource

Spring Data Access 文档

dependency

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>6.0.0</version>
</dependency>

to define a data source in a bean

@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource")
    public HikariDataSource dataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }
}

properties 配置

spring.datasource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/SpringBootDemo
spring.datasource.username=root
spring.datasource.password=jake1602
spring.datasource.maximum-pool-size=30

这里的链接池可以用 c3p0,HikariCP, 推荐使用 HikariCP 原因可以参考

  1. 性能最好
  2. 稳定,配置简单
  3. Spring 官方推荐连接池
  1. 集成 MyBatis

# MyBatis官方文档,集成SpringBoot

依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>3.0.2</version>
</dependency>
介绍了 MyBatis 的 essential components 和 大致的流程

MyBatis with Spring you need at least an SqlSessionFactory and at least one mapper interface.

MyBatis-Spring-Boot-Starter will:

  • Autodetect an existing DataSource
  • Will create and register an instance of a SqlSessionFactory passing that DataSource as an input using the SqlSessionFactoryBean
  • Will create and register an instance of a SqlSessionTemplate got out of the SqlSessionFactory
  • Auto-scan your mappers, link them to the SqlSessionTemplate and register them to Spring context so they can be injected into your beans
Mapper
@Mapper
public interface UserMapper {

    @Select("SELECT * FROM t_user WHERE id=#{id}")
    public User getUserById(@Param("id") Integer id);

    @Select("SELECT name FROM t_user WHERE id=#{id}")
    public String getUsernameById(@Param("id") Integer id);
}
注入 Mapper
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/getUsernameById")
    public String hello(@RequestParam(value = "id") Integer id) {
        System.out.println("userInterface : " + userMapper);
        String name = String.valueOf(userMapper.getUsernameById(id));
        return name;
    }
}

基础的SpringBoot + Mybatis + ConnectionPool 就集成完毕

Mybatis文档 还介绍了mybatis 的其他配置

MyBatis uses the prefix mybatis for its properties.

Available properties are:

PropertyDescription
config-locationLocation of MyBatis xml config file.
check-config-locationIndicates whether perform presence check of the MyBatis xml config file.
mapper-locationsLocations of Mapper xml config file.
type-aliases-packagePackages to search for type aliases. (Package delimiters are “,; \t\n”)
type-aliases-super-typeThe super class for filtering type alias. If this not specifies, the MyBatis deal as type alias all classes that searched from type-aliases-package.
type-handlers-packagePackages to search for type handlers. (Package delimiters are “,; \t\n”)
executor-typeExecutor type: SIMPLEREUSEBATCH
default-scripting-language-driverThe default scripting language driver class. This feature requires to use together with mybatis-spring 2.0.2+.
configuration-propertiesExternalized properties for MyBatis configuration. Specified properties can be used as placeholder on MyBatis config file and Mapper file. For detail see the MyBatis reference page.
lazy-initializationWhether enable lazy initialization of mapper bean. Set true to enable lazy initialization. This feature requires to use together with mybatis-spring 2.0.2+.
mapper-default-scopeDefault scope for mapper bean that scanned by auto-configure. This feature requires to use together with mybatis-spring 2.0.6+.
inject-sql-session-on-mapper-scanSet whether inject a SqlSessionTemplate or SqlSessionFactory bean (If you want to back to the behavior of 2.2.1 or before, specify false). If you use together with spring-native, should be set true(default).
configuration.*Property keys for Configuration bean provided by MyBatis Core. About available nested properties see the MyBatis reference page. NOTE: This property cannot be used at the same time with the config-location.
scripting-language-driver.thymeleaf.*Property keys for ThymeleafLanguageDriverConfig bean provided by MyBatis Thymeleaf. About available nested properties see the MyBatis Thymeleaf reference page.
scripting-language-driver.freemarker.*Properties keys for FreeMarkerLanguageDriverConfig bean provided by MyBatis FreeMarker. About available nested properties see the MyBatis FreeMarker reference page. This feature requires to use together with mybatis-freemarker 1.2.0+.
scripting-language-driver.velocity.*Properties keys for VelocityLanguageDriverConfig bean provided by MyBatis Velocity. About available nested properties see the MyBatis Velocity reference page. This feature requires to use together with mybatis-velocity 2.1.0+.

例如,如果想使用xml 配置sql,可以:

# application.properties
mybatis.mapper-locations=classpath:sqlmap/**/*.xml
...

xml配置

<!DOCTYPE mapper
                PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
                "https://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.mapper.UserMapper">
    <select id="getUsernameById" parameterType="int" resultType="string">
        SELECT name FROM t_user WHERE id = #{id}
    </select>
</mapper>

anyway,代码是最好的文档

github Mybatis spring boot starter是最好的文档