一、pom引入

  1. <dependency>
  2. <groupId>org.mybatis.spring.boot</groupId>
  3. <artifactId>mybatis-spring-boot-starter</artifactId>
  4. <version>2.1.4</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>mysql</groupId>
  8. <artifactId>mysql-connector-java</artifactId>
  9. <scope>runtime</scope>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.projectlombok</groupId>
  13. <artifactId>lombok</artifactId>
  14. <version>1.18.18</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.apache.commons</groupId>
  18. <artifactId>commons-lang3</artifactId>
  19. <version>3.8.1</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.apache.commons</groupId>
  23. <artifactId>commons-collections4</artifactId>
  24. <version>4.2</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>com.google.guava</groupId>
  28. <artifactId>guava</artifactId>
  29. <version>27.0.1-jre</version>
  30. </dependency>

二、yml配置

  1. # 数据源配置
  2. spring:
  3. datasource:
  4. driver-class-name: com.mysql.cj.jdbc.Driver
  5. url: jdbc:mysql://120.77.241.70:3306/test?characterEncoding=utf-8&useSSL=false
  6. username: root
  7. password: 123456
  8. # mybatis 配置
  9. mybatis:
  10. # xml文件
  11. mapper-locations: classpath:mapper/*.xml
  12. # type-aliases-package: com.afei.mybatis.model
  13. # 驼峰
  14. configuration:
  15. map-underscore-to-camel-case: true
  16. # type转换器配置
  17. type-handlers-package: com.afei.mybatis.interception

三、实现

1、启动类增加扫描mapper接口注解

  1. @MapperScan("com.afei.mybatis.mapper")

2、编写 xml、mapper接口

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="com.afei.mybatis.mapper.EmpMapper">
  4. <resultMap id="map" type="com.afei.mybatis.model.Emp" >
  5. <id column="id" property="id" />
  6. <result column="name" property="name" jdbcType="VARCHAR"/>
  7. <result column="age" property="age" jdbcType="INTEGER"/>
  8. <result column="status" property="status" jdbcType="VARCHAR" typeHandler="com.afei.mybatis.interception.EmpStatusEnumTypeHandler"/>
  9. </resultMap>
  10. <!-- typeHandler设置 -->
  11. <insert id="insertEmp">
  12. insert into emp(name,age,status) values(#{name},#{age},#{status,typeHandler=com.afei.mybatis.interception.EmpStatusEnumTypeHandler})
  13. </insert>
  14. <select id="selectList" resultMap="map">
  15. SELECT * FROM emp
  16. </select>
  17. </mapper>
  1. public interface EmpMapper {
  2. List<Emp> selectList();
  3. void insertEmp(Emp emp);
  4. }