学习 Spring Boot(二):集成 MyBatis 和 Druid

简介

MyBatis 是基于 Java 的 ORM 框架,通过 Mapper 实现了 SQL 与 POJO 之间的映射。

依赖

编辑 pom.xml 文件:

定义 MyBatis 和 MySQL Driver 版本属性:

<spring-boot-starter-mybatis.version>1.3.0</mybatis.version>  
<mysql.driver.version>5.1.39</mysql.driver.version>  

添加依赖:

<dependency>  
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>  
<dependency>  
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>${spring-boot-starter-mybatis}</version>
</dependency>  
<dependency>  
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.driver.version}</version>
</dependency>  

配置数据源

数据源使用阿里巴巴开源的数据库连接池 Druid

编辑 application.yml 文件,定义数据源:

spring:  
  datasource:
    name: mysql
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:8020/app?useUnicode=true&characterEncoding=utf-8
    username: me
    password: pass

# Druid
druid:  
  initial-size: 1
  min-idle: 1
  max-active: 20

编辑 DataSourceConfiguration.java 文件:

@Configuration
public class DataSourceConfiguration {

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${druid.initial-size}")
    private Integer initialSize;

    @Value("${druid.min-idle}")
    private Integer minIdle;

    @Value("${druid.max-active}")
    private Integer maxActive;

    @Bean
    @Primary
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();

        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);

        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxActive(maxActive);

        return dataSource;
    }

}

数据库

创建表 users,定义字段:

  • id 主键
  • name 姓名
  • sex 性别
create table demo.users  
(
    id int auto_increment
        primary key,
    name varchar(32) null,
    sex char null
)
;

实体

根据表 users 创建实体类 User.java

public class User {

    private Integer id;

    private String name;

    private String sex;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

}

Mapper

MyBatis 支持两种方式定义 Mapper,一种是通过 XML 配置,另一种是通过 Java 注解。

XML 配置 Mapper

编辑 application.yml,配置 MyBatis Mapper 配置文件 *Mapper.xml 所在位置和实体所在的包:

mybatis:  
  mapper-locations: classpath*:**/mappers/*Mapper.xml
  type-aliases-package: com.dyingbleed.demo.entity

创建表 users 的映射接口 UserMapper.java

@Mapper
public interface UserMapper {

    public List<User> queryAllUsers();

    public List<User> queryUsersByName(@Param("name") String name);

}

创建 UserMapper 的 Mapper 配置文件:

<?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.dyingbleed.spring.test.mapper.UserMapper">

    <select id="queryAllUsers" resultType="User">
        SELECT * FROM users
    </select>

    <select id="queryUsersByName" resultType="User">
        SELECT * FROM users WHERE name LIKE '%'|#{name}|'%'
    </select>

</mapper>  

注解配置 Mapper

编辑 ApplicationConfiguration.java,配置 Mapper 扫描目录:

@Configuration
@EnableAutoConfiguration
@ComponentScan
@MapperScan(basePackages = "com.muziyuchen.app.mapper")
public class ApplicationConfiguration {  
    // do something
}

创建表 users 的映射接口 UserMapper.java

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users")
    public List<User> findAllUsers();

    @Select("SELECT * FROM users WHERE name LIKE '%'|#{name}|'%'")
    public List<User> findUsersByName(@Param("name") String name);

}