SpringBoot整合MyBatis超详细教程

 更新时间:2021年5月12日 15:00  点击:1562

1.整合MyBatis操作

前面一篇提到了SpringBoot整合基础的数据源JDBC、Druid操作,实际项目中更常用的还是MyBatis框架,而SpringBoot整合MyBatis进行CRUD也非常方便。

下面从配置模式、注解模式、混合模式三个方面进行说明MyBatis与SpringBoot的整合。

1.1.配置模式

MyBatis配置模式是指使用mybatis配置文件的方式与SpringBoot进行整合,相对应的就有mybatis-config.xml(用于配置驼峰命名,也可以省略这个文件)、XxxMapper.xml文件。

主要步骤为:

  • 导入mybatis官方starter
  • 编写mapper接口。标准@Mapper注解
  • 编写sql映射文件并绑定mapper接口

在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息 (建议;配置在mybatis.configuration中,可以省略mybatis-config.xml文件)

下面是具体整合配置步骤:

①引入相关依赖pom.xml配置:

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--整合mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

②编写对应Mapper接口:

@Mapper  //这个注解表示了这个类是一个mybatis的mapper接口类
@Repository
public interface UserMapper {
    //@Select("select * from user")
    List<User> findAllUsers();

    //@Insert("insert into user(id, username, password) values (#{id}, #{username}, #{password})")
    void insert(User user);

    //@Update("update user set username = #{username}, password = #{password} where id = #{id}")
    void update(User user);

    //@Delete("delete from user where id = #{id}")
    void deleteById(Integer id);
}

③在resources下创建对应的mapper文件,对应domain类,数据库表单如下:

User类:

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
}

数据库user表:

UserMapper.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">
<!--namespace表示当前mapper的唯一标识:一般使用domain的全路径名+Mapper来命名-->
<mapper namespace="com.fengye.springboot_mybatis.mapper.UserMapper">
    <!--id:方法表示,一般配置对应的方法;
        resultType:表示该方法有返回,返回需要封装到对应实体的类型-->
    <select id="findAllUsers" resultType="com.fengye.springboot_mybatis.entity.User">
        select * from user
    </select>

    <insert id="insert" parameterType="com.fengye.springboot_mybatis.entity.User">
        insert into user(id, username, password) values (#{id}, #{username}, #{password})
    </insert>

    <update id="update" parameterType="com.fengye.springboot_mybatis.entity.User">
        update user set username = #{username}, password = #{password} where id = #{id}
    </update>

    <delete id="deleteById" parameterType="Integer">
        delete from user where id = #{id}
    </delete>
</mapper>

④对应配置application.yml文件:

application.yml

server:
  port: 8083

spring:
  datasource:
    username: root
    password: admin
    #假如时区报错,增加时区配置serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/mybatis02_0322?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  #config-location: classpath:mybatis/mybatis-config.xml  使用了configuration注解则无需再指定mybatis-config.xml文件
  mapper-locations: classpath:mybatis/mapper/*.xml
  configuration:   #指定mybatis全局配置文件中的相关配置项
    map-underscore-to-camel-case: true

1.2.注解模式

注解模式使用

主要步骤:

  • 导入mybatis官方依赖
  • 注解方式编写mapper接口
  • 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息

可以看到注解模式比配置模式少了编写Mapper.xml文件,简化了简单SQL语句的xml文件编写。

下面是具体整合步骤:

①创建测试表单city,对应domain类:

建表sql:

CREATE TABLE city
(
    id    INT(11) PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(30),
    state VARCHAR(30),
    country VARCHAR(30)
);

City类:

@Data
public class City {
    private Long id;
    private String name;
    private String state;
    private String country;
}

②导入pom.xml与配置模式相同,编写注解式CityMapper接口:

@Mapper
@Repository
public interface CityMapper {
    @Select("select * from city where id = #{id}")
    public City getCityById(Long id);

    /**
     * 使用@Options来增加除Insert语句中其它可选参数,比如插入获取id主键的值
     * @param city
     */
    @Insert("insert into city(name, state, country) values (#{name}, #{state}, #{country})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    public void insert(City city);

    @Update("update city set name = #{name}, state = #{state}, country = #{country} where id = #{id}")
    public void update(City city);

    @Delete("delete from city where id = #{id}")
    public void deleteById(Long id);
}

③编写Service层、Controller层:

Service相关:

public interface CityService {
    City findCityById(Long id);

    void insert(City city);

    void update(City city);

    void deleteById(Long id);
}


@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityMapper cityMapper;

    @Override
    public City findCityById(Long id) {
        return cityMapper.getCityById(id);
    }

    @Override
    public void insert(City city) {
        cityMapper.insert(city);
    }

    @Override
    public void update(City city) {
        cityMapper.update(city);
    }

    @Override
    public void deleteById(Long id) {
        cityMapper.deleteById(id);
    }
}

Controller相关:

@RestController
@RequestMapping("/city/api")
public class CityController {
    @Autowired
    private CityService cityService;

    @RequestMapping("/findCityById/{id}")
    public City findCityById(@PathVariable("id") Long id){
        return cityService.findCityById(id);
    }

    @PostMapping("/insert")
    public String insert(City city){
        cityService.insert(city);
        return "insert ok";
    }

    @PostMapping("/update")
    public String update(City city){
        cityService.update(city);
        return "update ok";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id){
        cityService.deleteById(id);
        return "delete ok";
    }
}

④对应使用Postman接口进行测试:

简单模拟接口POST/GET请求即可:

1.3.混合模式

在实际项目开发中涉及很多复杂业务及连表查询SQL,可以配合使用注解与配置模式,达到最佳实践的目的。

实际项目操作步骤:

  • 引入mybatis-starter
  • 配置application.yaml中,指定mapper-location位置即可
  • 编写Mapper接口并标注@Mapper注解
  • 简单方法直接注解方式
  • 复杂方法编写mapper.xml进行绑定映射
  • 主启动类上使用@MapperScan("com.fengye.springboot_mybatis.mapper") 简化Mapper接口,包下所有接口就可以不用标注@Mapper注解

具体配置如下:

@SpringBootApplication
//主启动类上标注,在XxxMapper中可以省略@Mapper注解
@MapperScan("com.fengye.springboot_mybatis.mapper")
public class SpringbootMybatisApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }

}


@Repository
public interface CityMapper {
    @Select("select * from city where id = #{id}")
    public City getCityById(Long id);

    /**
     * 使用@Options来增加除Insert语句中其它可选参数,比如插入获取id主键的值
     * @param city
     */
    @Insert("insert into city(name, state, country) values (#{name}, #{state}, #{country})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    public void insert(City city);

    @Update("update city set name = #{name}, state = #{state}, country = #{country} where id = #{id}")
    public void update(City city);

    @Delete("delete from city where id = #{id}")
    public void deleteById(Long id);
}

本博客参考写作文档:

SpringBoot2核心技术与响应式编程

博客涉及代码示例均已上传至github地址:

SpringBootStudy

到此这篇关于SpringBoot整合MyBatis超详细教程的文章就介绍到这了,更多相关SpringBoot整合MyBatis内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章

  • Mybatis Plus select 实现只查询部分字段

    这篇文章主要介绍了Mybatis Plus select 实现只查询部分字段的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-01
  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28
  • 解决Mybatis 大数据量的批量insert问题

    这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
  • mybatis的Configuration详解

    这篇文章主要介绍了mybatis的Configuration详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-04
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • mybatis 返回Integer,Double,String等类型的数据操作

    这篇文章主要介绍了mybatis 返回Integer,Double,String等类型的数据操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-25
  • SpringBoot集成Redis实现消息队列的方法

    这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • 详解springBoot启动时找不到或无法加载主类解决办法

    这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • 解决Springboot get请求是参数过长的情况

    这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • Spring Boot项目@RestController使用重定向redirect方式

    这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02
  • MyBatis-Plus的物理删除和逻辑删除(使用场景)

    数据库中的数据删除会分为两种:物理删除 和 逻辑删除,接下来通过本文给大家介绍MyBatis-Plus的物理删除和逻辑删除使用场景分析,感兴趣的朋友一起看看吧...2021-09-25
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • Springboot如何使用mybatis实现拦截SQL分页

    这篇文章主要介绍了Springboot使用mybatis实现拦截SQL分页,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-19
  • mybatis-plus雪花算法自动生成机器id原理及源码

    Mybatis-Plus是一个Mybatis的增强工具,它在Mybatis的基础上做了增强,却不做改变,Mybatis-Plus是为简化开发、提高开发效率而生,但它也提供了一些很有意思的插件,比如SQL性能监控、乐观锁、执行分析等,下面一起看看mybatis-plus雪花算法自动生成机器id原理解析...2021-06-04
  • 解决Mybatis中mapper.xml文件update,delete及insert返回值问题

    这篇文章主要介绍了解决Mybatis中mapper.xml文件update,delete及insert返回值问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-23
  • springboot中使用@Transactional注解事物不生效的坑

    这篇文章主要介绍了springboot中使用@Transactional注解事物不生效的原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • 详解SpringBoot之访问静态资源(webapp...)

    这篇文章主要介绍了详解SpringBoot之访问静态资源(webapp...),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-14
  • Mybatis plus中使用in查询出错如何解决

    这篇文章主要介绍了Mybatis plus中使用in查询出错的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-08-06
  • Mybatis执行update失败的解决

    这篇文章主要介绍了Mybatis执行update失败的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-01