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

【java框架】SpringBoot(7) -- SpringBoot整合MyBatis的更多相关文章

  1. 【springboot spring mybatis】看我怎么将springboot与spring整合mybatis与druid数据源

    目录 概述 1.mybatis 2.druid 壹:spring整合 2.jdbc.properties 3.mybatis-config.xml 二:java代码 1.mapper 2.servic ...

  2. SpringBoot 2.X整合Mybatis

    1.创建工程环境 勾选Web.Mybatis.MySQL,如下 依赖如下 <dependency> <groupId>org.springframework.boot</ ...

  3. SpringBoot | 3.2 整合MyBatis

    目录 前言 1. 导入MyBatis场景 1.1 初始化导向 1.2 手动导入 2. *MyBatis自动配置原理 3. 全局配置文件 @Mapper @MapperScan 3.1 配置模式 3.2 ...

  4. SpringBoot当中如何整合mybatis和注入

    [学习笔记] 6.整合mybatis和注入: 马克-to-win@马克java社区: 根据第3部分的helloworld例子,用那个项目做底子.pom.xml只需要加入mybatis和mysql的部分 ...

  5. SpringBoot学习之整合Mybatis

    本博客使用IDEA开发工具,通过Maven构建SpringBoot项目,初始化项目添加的依赖有:spring-boot-starter-jdbc.spring-boot-starter-web.mys ...

  6. springboot笔记07——整合MyBatis

    前言 Springboot 整合 MyBatis 有两种方式,分别是:"全注解版" 和 "注解.xml混合版". 创建项目 创建Springboot项目,选择依 ...

  7. springboot学习2 整合mybatis

    springboot整合mybatis 一.添加mybatis和数据库连接的依赖 <!--整合mybatis--> <dependency> <groupId>or ...

  8. 利用IDEA搭建SpringBoot项目,整合mybatis

    一.配置文件.启动项目 生成之后这几个文件可以删掉的 配置application spring.datasource.url=jdbc:mysql://localhost:3306/test?serv ...

  9. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  10. SpringBoot: 10.整合mybatis(转)

    需求:通过使用 SpringBoot+SpringMVC+MyBatis 整合实现一个对数据库中的 t_user 表的 CRUD 的操作 1.创建maven项目,添加项目所需依赖 <!--spr ...

随机推荐

  1. Python中的描述器

    21.描述器:Descriptors 1)描述器的表现 用到三个魔术方法.__get__()   __set__()  __delete__() 方法签名如下: object.__get__(self ...

  2. PTA 数组元素的区间删除

    6-6 数组元素的区间删除 (20 分)   给定一个顺序存储的线性表,请设计一个函数删除所有值大于min而且小于max的元素.删除后表中剩余元素保持顺序存储,并且相对位置不能改变. 函数接口定义: ...

  3. 谷歌SRE运维模式解读

    谷歌SRE运维模式解读 前面我和你分享了一些关于运维组织架构和协作模式转型的内容,为了便于我们更加全面地了解先进的运维模式,今天我们再来谈一下谷歌的SRE(Site Reliability Engin ...

  4. 基于阿里云托管kubernetes的版本升级

    前言 因为阿里云的knative对应得k8s版本大于1.15,而我们目前得集群环境是1.14.8,因此需要对预发环境进行版本升级.基于aliyun托管的kubernetes集群版本升级本没有什么可写, ...

  5. 三分钟玩转微软AI量化投资开源库QLib

    更多精彩内容,欢迎关注公众号:数量技术宅,也可添加技术宅个人微信号:sljsz01,与我交流. 微软QLib简介 微软亚洲研究院发布了 AI 量化投资开源平台"微矿 Qlib".Q ...

  6. 轻松理解 Java 静态代理/动态代理

    目录 什么是代理模式 定义 代理模式的主要角色 优点 缺点 静态代理 动态代理 JDK原生动态代理 例子 分析 小结 CGLIB动态代理 例子 分析 final类型 其他方案 尾声 理解Java动态代 ...

  7. 可读性友好的JavaScript:两个专家的故事

    每个人都想成为专家,但什么才是专家呢?这些年来,我见过两种被称为"专家"的人.专家一是指对语言中的每一个工具都了如指掌的人,而且无论是否有帮助,都一定要用好每一点.专家二也知道每一 ...

  8. OO_Unit4_Summary暨课程总结

    初始oo,有被往届传言给吓到:oo进行中,也的确有时会被作业困扰(debug到差点放弃):而oo即将结束的此刻,却又格外感慨这段oo历程. 一.单元架构设计 本单元任务是设计一个UML解析器,能够支持 ...

  9. 安卓安装kali linux之Termux

    解决安装kali无模组问题 https://blog.csdn.net/weixin_44690490/article/details/108599693?utm_source=app 步骤 1.获取 ...

  10. JVM经典垃圾收集器

      这个关系不是一成不变的,由于维护和兼容性测试的成本,在JDK 8时将Serial+CMS. ParNew+Serial Old这两个组合声明为废弃(JEP 173),并在JDK 9中完全取消了这些 ...