整合MyBatis實例

  • 2019 年 10 月 7 日
  • 筆記

這篇文章講解一下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