Spring Boot 2 实践记录之 MySQL + MyBatis 配置

如果不需要连接池,那么只需要简单的在pom文件中,添加mysql依赖:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>xxx.xxx.xxx</version>
</dependency>

然后在配置文件中添加配置:

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://hostname:port/xxxxxx?autoReconnect=true&failOverReadOnly=false&useSSL=false&allowMultiQueries=true&rewriteBatchedStatements=true
spring.datasource.username=xxxxxx
spring.datasource.password=xxxxxx

MySQL datasource 就配置完了。

如果使用连接池,则需要一个数据库配置类,如下是使用 PooledDataSource 的 Java 配置文件:

package cn.liuxingwei.judge.config;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 数据源相关配置
 * @author liuxingwei
 */
@Configuration
@EnableTransactionManagement
public class DataConfiguration {

    /**
     * mysql driver 变量,取自外挂配置文件
     * @author liuxingwei
     */
    @Value("${spring.datasource.driver-class-name}")
    private String mysqlDriver;

    /**
     * mysql 连接 url,取自外挂配置文件
     * @author liuxingwei
     */
    @Value("${spring.datasource.url}")
    private String mysqlUrl;

    /**
     * mysql 连接用户名,取自外挂配置文件
     * @author liuxingwei
     */
    @Value("${spring.datasource.username}")
    private String mysqlUsername;

    /**
     * mysql 连接密码,取自外挂配置文件
     */
    @Value("${spring.datasource.password}")
    private String mysqlPassword;

    /**
     * 数据源(dataSource)定义
     * @author liuxingwei
     * @return DataSource
     */
    @Bean
    public PooledDataSource dataSource() {
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver(mysqlDriver);
        dataSource.setUrl(mysqlUrl);
        dataSource.setUsername(mysqlUsername);
        dataSource.setPassword(mysqlPassword);
        return dataSource;
    }

}

MyBatis 也不需要特殊的配置,只要在pom中加上依赖:

<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>xxx.xxx.xxx</version>
</dependency>

然后分别创建实体类、Mapper 接口和 Mapper XML 文件,就可以使用了。附上一个可用于 Eclipse 的 MyBatis Generator 插件的配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="MySqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="autoDelimitKeywords" value="true"/>
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="addRemarkComments" value="true"/>
        </commentGenerator>
       <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://hostname:port/judge?autoReconnect=true&amp;failOverReadOnly=false&amp;useSSL=false&amp;allowMultiQueries=true&amp;rewriteBatchedStatements=true"
                        userId="root"
                        password="123456"></jdbcConnection>
        <javaModelGenerator targetPackage="cn.liuxingwei.judge.domain"
                            targetProject="judge/src/main/java">
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="cn.liuxingwei.judge.mapper"
                         targetProject="judge/src/main/resources"/>
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="cn.liuxingwei.judge.mapper"
                             targetProject="judge/src/main/java"/>
        <table tableName="%">
            <generatedKey column="id" sqlStatement="MySql"/>
            <domainObjectRenamingRule searchString="^T" replaceString="" />
        </table>
    </context>
</generatorConfiguration>

顺便提一句,如果数据库的字符编码为 UTF8,可以在连接 url 中添加 characterEncoding=UTF-8 来实现,不必管 MySQL 服务器本身的设置:

spring.datasource.url=jdbc:mysql://hostname:port/xxx?characterEncoding=UTF8&autoReconnect=true&failOverReadOnly=false

但是如果数据库编码为 UTF8MB4,是不能简单地把连接串中的 UTF8 换成 UTF8MB4 的,会报错,只能是在 MySQL 的配置文件(my.cnf)中将 MySQL 的默认字符集设置为 utf8mb4,连接串中不再设置 characterEncoding。

posted on 2019-02-13 22:24  刘兴伟  阅读(388)  评论(0编辑  收藏  举报

导航