本博客中介绍了两种整合方式,分别是xml配置和注解

依赖

<dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <scope>runtime</scope>
         </dependency>
         
         <!-- mybatis -->
         <dependency>
             <groupId>org.mybatis.spring.boot</groupId>
             <artifactId>mybatis-spring-boot-starter</artifactId>
             <version>1.3.0</version>
         </dependency>
         
         <!-- 数据源 -->
           <dependency>
             <groupId>com.alibaba</groupId>
             <artifactId>druid</artifactId>
             <version>1.0.19</version>
         </dependency>



这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖。

 

MyBatis-Spring-Boot-Starter依赖将会提供如下

  • 自动检测现有的DataSource
  • 将创建并注册SqlSessionFactory的实例,该实例使用SqlSessionFactoryBean将该DataSource作为输入进行传递
  • 将创建并注册从SqlSessionFactory中获取的SqlSessionTemplate的实例。
  • 自动扫描您的mappers,将它们链接到SqlSessionTemplate并将其注册到Spring上下文,以便将它们注入到您的bean中。

就是说,使用了该Starter之后,只需要定义一个DataSource即可(application.properties中可配置),它会自动创建使用该DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。会自动扫描你的Mappers,连接到SqlSessionTemplate,并注册到Spring上下文中。

 

数据源配置

spring.datasource.url=jdbc:mysql://localhost:3306/test
 spring.datasource.username = root
 spring.datasource.password = XXXX
 spring.datasource.driver-class-name = com.mysql.jdbc.Driver


 

运行类

package com.gwd;
 import javax.sql.DataSource;
  
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.context.annotation.Bean;
 import org.springframework.core.env.Environment;
  
 import com.alibaba.druid.pool.DruidDataSource;
  
 @SpringBootApplication
 public class SpringBootTestApplication {
     public static void main(String[] args) {
         SpringApplication.run(SpringBootTestApplication.class, args);
     }
  
     @Autowired
     private Environment env;
  
     //destroy-method="close"的作用是当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.
     @Bean(destroyMethod =  "close")
     public DataSource dataSource() {
         DruidDataSource dataSource = new DruidDataSource();
         dataSource.setUrl(env.getProperty("spring.datasource.url"));
         dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名
         dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码
         dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
         dataSource.setInitialSize(2);//初始化时建立物理连接的个数
         dataSource.setMaxActive(20);//最大连接池数量
         dataSource.setMinIdle(0);//最小连接池数量
         dataSource.setMaxWait(60000);//获取连接时最大等待时间,单位毫秒。
         dataSource.setValidationQuery("SELECT 1");//用来检测连接是否有效的sql
         dataSource.setTestOnBorrow(false);//申请连接时执行validationQuery检测连接是否有效
         dataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。
         dataSource.setPoolPreparedStatements(false);//是否缓存preparedStatement,也就是PSCache
         return dataSource;
     }
 }


 

bean

package com.gwd.domain;
  
 public class User {
     private Integer id;
  
     private String name;
  
     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 == null ? null : name.trim();
     }
 }
 Servicepackage com.gwd.service;
  
 import com.gwd.domain.User;
  
 public interface StuService {
     public User getById(int id);
 }



ServiceImpl(和Spring中无二,务必加@Service)

package com.gwd.service.impl;
  
 import java.io.Serializable;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 import com.gwd.dao.StuMapper;
 import com.gwd.domain.User;
 import com.gwd.service.StuService;
 @Service
 public class StuServiceImpl implements StuService,Serializable{
     /**
      * 
      */
     private static final long serialVersionUID = 1L;
     @Autowired
     private StuMapper stuMapper;
     @Override
     public User getById(int id) {
         // TODO Auto-generated method stub
         User user = stuMapper.selectById(id);
         return user;
     }
 }
 Controllerpackage com.gwd.controller;
  
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.bind.annotation.RestController;
 import com.gwd.domain.User;
 import com.gwd.service.StuService;
  
 @RestController
 public class StuController {
     @Autowired
     private StuService stuService;
     
     @RequestMapping("/index")
     @ResponseBody
     public String index() {
         User stu = stuService.getById(1);
         return stu.getName();
     }
 }


 

—————————————————————————————————————一.XML配置方式

项目结构图

springboot整合mybatis(Mapper.xml和注解两种方式)_mybatis

 

Application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test
 spring.datasource.username = root
 spring.datasource.password = XXXX
 spring.datasource.driver-class-name = com.mysql.jdbc.Driver
 mybatis.mapper-locations=classpath:mapper/*.xml
 mybatis.type-aliases-package=com.gwd.domain
 logging.file=/log/springBootTest.log
 server.port=8090


 

Dao

package com.gwd.dao;
  
 import org.apache.ibatis.annotations.Mapper;
  
 import com.gwd.domain.User;
  
 @Mapper
 public interface StuMapper {
     User selectById(int id);
 }


 

注:这边的@Mapper注解也可以不用,直接在运行类上加上@MapperScan(basePackages= {"xxx.xxx.mapper"}),并且推荐使用后者,比较方便,具体如下图

springboot整合mybatis(Mapper.xml和注解两种方式)_注解_02

 

 

StuMapper.xml(规则和spring整合mybatis一致)

 

该文件放置到resources文件夹下面,并且需要在Application.properties文件中配置文件地址

<?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.gwd.dao.StuMapper" >
   <resultMap id="BaseResultMap" type="com.gwd.domain.User" >
     <result column="id" property="id" jdbcType="INTEGER" />
     <result column="name" property="name" jdbcType="VARCHAR" />
   </resultMap>
   <sql id="Base_Column_List" >
     id, name
   </sql>
   <select id="selectById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
       select * from stu where id=#{id}
   </select>
 </mapper>


 

————————————————————————————————————————————————————————

二.注解方式

Application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test
 spring.datasource.username = root
 spring.datasource.password = 19940315
 spring.datasource.driver-class-name = com.mysql.jdbc.Driver
 mybatis.type-aliases-package=com.gwd.domain
 logging.file=/log/springBootTest.log
 server.port=8090


 

项目结构

 

springboot整合mybatis(Mapper.xml和注解两种方式)_注解_03

 

Dao(无需Mapper.xml)

package com.gwd.dao;
  
 import org.apache.ibatis.annotations.*;
 import com.gwd.domain.User;
  
 @Mapper
 public interface StuMapper {
     @Select("select * from stu where id = #{id}")
     @Results(id = "userMap", value = {
             @Result(column = "id", property = "id", javaType = Integer.class),
             @Result(property = "name", column = "name", javaType = String.class)
     })
     User selectById(@Param("id")int id);
 }