玩转springboot:整合mybatis实例

这篇文章讲解一下springboot整合mybatis,其实,springboot整合mybatis和springmvc整合mybatis并没有什么太大的区别,大体上还是差不多哦,只是比springmvc更加的简单一点,下面我们就以一个例子来讲解一下整合mybatis。

我们先看一下pom.xml

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

因为mybatis已经整合到starter中了,所以我们只需要引入这个依赖就可以了。

下面,我们以Employee员工为例

public class Employee {

    private Integer id;
    private String lastName;
    private Integer gender;
    private String email;
    private Integer dId;
    //getter setter
}
  • 数据层接口(注解版)
//@Mapper或者@MapperScan将接口扫描装配到容器中
@Mapper
public interface EmployeeMapper {

    @Select("select * from employee where id=#{id}")
    public Employee getEmpById(Integer id);

    @Insert("Insert into employee(email) values(#{email})")
    public void insertEmp(Employee employee);
}

上面这是以注解的方式进行配置,当然我们也可以使用配置文件

  • 数据层(配置文件版)
//@Mapper或者@MapperScan将接口扫描装配到容器中
public interface EmployeeMapper {

    public Employee getEmpById(Integer id);

    public void insertEmp(Employee employee);
}

因为是配置文件版,所以我们需要配置mapper配置文件

  • EmployeeMapper.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.sihai.springboot.mapper.EmployeeMapper">

   <!--    public Employee getEmpById(Integer id);
    public void insertEmp(Employee employee);-->
    <select id="getEmpById" resultType="com.sihai.springboot.bean.Employee">
        SELECT * FROM employee WHERE id=#{id}
    </select>

    <insert id="insertEmp">
        INSERT INTO employee(email) VALUES (#{email})
    </insert>
</mapper>

我们在看一下mybatis数据源的配置,我们这里使用yml的方式,数据源使用druid,配置如下

  • 数据源配置application.yml
spring:
  datasource:
#   数据源基本配置
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://192.168.15.22:3306/mybatis
    type: com.alibaba.druid.pool.DruidDataSource
#   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
#   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
  # 指定全局配置文件位置
  config-location: classpath:mybatis/mybatis-config.xml
  # 指定sql映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml

这就是mybatis整合springboot 的过程了,要了解mybatis的用法,请查看下面的文章mybatis系列文章

猜你喜欢

转载自blog.csdn.net/sihai12345/article/details/81224819