springboot 学习之集成mybatis

119 阅读1分钟

springboot 学习之集成mybatis

1、前言

spring data jpa针对单独的表使用注解开发比较简单,笔者一直以为mybatis才是持久层正确的打开方式。下面整理一下springboot集成mybatis。

2、开发准备

引入依赖:(也可以使用插件直接选择)

<!-- mybtais 集成依赖 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

3、yml配置

# server
server:
  port: 8081
  servlet:
    context-path: /boot

# database
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test
    driver-class-name:  com.mysql.jdbc.Driver
    username: root
    password: root

# mybatis
mybatis:
  config-location: classpath:templates/mybatis/mybatis-config.xml  #mybatis配置,驼峰匹配、打印SQL等
  mapper-locations: classpath:templates/mybatis/mapper/*.xml       #SQL查询文件
  type-aliases-package: ws.simonking.springboot.mybatis.model      #别名扫描包

4、mapper.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="ws.simonking.springboot.mybatis.mapper.UserInfoMapper" >
  <!-- 这里配置了resultMap,数据库字段和属性一一对应就不用开启驼峰匹配了 -->
  <resultMap id="BaseResultMap" type="ws.simonking.springboot.mybatis.model.UserInfo" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="sex" property="sex" jdbcType="VARCHAR" />
    <result column="job" property="job" jdbcType="VARCHAR" />
    <result column="birthday" property="birthday" jdbcType="TIMESTAMP" />
    <result column="created_time" property="createdTime" jdbcType="TIMESTAMP" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
  </resultMap>

  <sql id="Base_Column_List" >
    id, `name`, age, sex, job, birthday, created_time, update_time
  </sql>
  <select id="getUserInfoById" resultMap="BaseResultMap" parameterType="java.lang.Integer">
      select
      <include refid="Base_Column_List" />
      from user_info
      where id = #{id}
  </select>
</mapper>

5、mapper

public interface UserInfoMapper{
    UserInfo getUserInfoById(Integer id);
}

注意:有些技术文档使用单独的注解@Mapper或者@Repository。直接将UserInfoMapper标注为mapper接口。但是笔者使用后项目报错,无法启动。笔者采用的而是使用接口扫描的方式初始化Mapper的(加在启动方法上)。

6、启动方法修改

@SpringBootApplication
@MapperScan("ws.simonking.springboot.mybatis.mapper") // 添加接口扫描,注册mapper
public class SpringbootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }
}

7、启动

访问测试即可成功!