针对有编程基础,开始学习微服务的同学,我们陆续推出从0学微服务的笔记分享。力求从各个中间件的使用来反思这些中间件的作用和优势。
会分享的比较快,会记录demo演算和中间件的使用过程,至于细节的理论知识请自主查阅相关资料并学习。满是干货,注意查收。
本期我们开始学习MyBatis-Plus。
了解 MyBatis 基础:虽然 MyBatis-Plus 是 MyBatis 的增强版,但建议先了解 MyBatis 的基本原理和用法,这有助于更好地理解 MyBatis-Plus。
阅读官方文档:MyBatis-Plus 的官方文档是学习的最佳资源,包含了安装、配置、使用、插件等各方面的内容。
搭建开发环境:可以使用 Spring Boot 快速搭建一个 MyBatis-Plus 的开发环境,并尝试运行一些示例代码。
学习 CRUD 操作:MyBatis-Plus 提供了丰富的 CRUD 方法,包括基本的增删改查以及批量操作等,需要熟练掌握。
掌握条件构造器:MyBatis-Plus 的条件构造器是其一大亮点,可以很方便地构造复杂的 SQL 语句,需要重点学习。
使用插件:了解并尝试使用 MyBatis-Plus 提供的各种插件,如分页插件、性能分析插件等,以提高开发效率和系统性能。
实践项目:通过参与实际项目,将 MyBatis-Plus 应用到具体的业务场景中,以加深对其的理解和掌握。
由于本文阅读对象是已经有其他语言或框架的编程基础的人,所以我们快速的开始一个Demo来变做变学,以战代练。
我们创建一个MP项目,环境选择:
jdk选择了1.8,spring boot版本2.6.13,mysql5.7
1.8 UTF-8 UTF-8 2.6.13 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-web mysql mysql-connector-java 8.0.29 com.baomidou mybatis-plus-boot-starter 3.5.1 org.springframework.boot spring-boot-starter-test test
# 应用服务 WEB 访问端口 server.port=8080 # 数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3316/mytest?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=**** spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
package com.example.mp.repository.mapper; import com.example.mp.model.Student; import org.apache.ibatis.annotations.Mapper; @Mapper public interface StudentMapper { Student findById(Long id); void save(Student student); void update(Student student); void delete(Long id); }
@Mapper
注解是MyBatis框架中的一个注解,用于标识一个接口为MyBatis的Mapper接口。MyBatis的Mapper接口用于定义数据库操作的方法,这些方法可以通过XML文件或注解来定义SQL语句。
以下是@Mapper
注解的一些主要用途:
自动扫描Mapper接口: 当你使用@Mapper
注解标记一个接口时,MyBatis会自动扫描这个接口,并将其注册为一个Mapper。这意味着你不需要手动配置Mapper接口的位置。
简化SQL语句的定义: 在Mapper接口中,你可以使用注解来定义SQL语句,而不需要编写XML文件。例如,你可以使用@Select
、@Insert
、@Update
和@Delete
注解来定义查询、插入、更新和删除操作。
支持动态SQL: MyBatis的Mapper接口支持动态SQL,这意味着你可以在SQL语句中添加条件、循环等逻辑,以适应不同的查询需求。
以下是一个使用@Mapper
注解的例子:
@Mapper public interface StudentMapper { @Select("SELECT * FROM students WHERE id = #{id}") Student findById(Long id); @Insert("INSERT INTO students(name, age) VALUES(#{name}, #{age})") void save(Student student); @Update("UPDATE students SET name=#{name}, age=#{age} WHERE id=#{id}") void update(Student student); @Delete("DELETE FROM students WHERE id=#{id}") void delete(Long id); }
但是看到我之前贴的代码里,SQL语句并不包含在接口代码中,那么SQL去哪里了呢?其实刚才说了,@Mapper
注解也可以通过XML文件定义SQL语句。细心点的可以看到工程目录里,有个src/main/resources/mapper/StudentMapper.xml,通过@Mapper
注解可以关联到他。
INSERT INTO student (id, name, age) VALUES (#{id}, #{name}, #{age}) UPDATE student SET name = #{name}, age = #{age} WHERE id = #{id} DELETE FROM student WHERE id = #{id}
在MyBatis(包括MyBatis-Plus)中,Mapper的XML文件提供了一种灵活的方式来定义SQL语句,特别是当SQL语句变得复杂或需要动态构建时。这种方法允许开发者将SQL语句与Java代码分离,使得SQL语句的编写、修改和调试变得更加容易。
、
、
、
、
等标签),可以轻松地处理各种复杂的查询和更新逻辑。在MyBatis社区中,使用XML文件来定义SQL语句是非常流行和推荐的做法。尽管MyBatis-Plus提供了许多便捷的CRUD操作和条件构造器,但在处理复杂查询和更新时,XML文件仍然是一个强大的工具。
定义Mapper接口:首先,你需要定义一个Mapper接口,该接口中的方法将对应于XML文件中的SQL语句。
编写XML文件:然后,在src/main/resources
目录下的相应包路径中创建一个XML文件,文件名需要与Mapper接口的全路径名相同,但后缀为.xml
。
映射SQL语句:在XML文件中,使用
标签作为根元素,并使用、
、
、
等标签来定义SQL语句。你可以使用id
属性来指定该SQL语句对应的Mapper接口中的方法名。
使用动态SQL:如果SQL语句需要根据条件动态构建,可以使用MyBatis提供的动态SQL标签(如
、
等)来实现。
配置Mapper扫描:确保你的MyBatis或MyBatis-Plus配置中包含了Mapper接口的扫描路径,这样MyBatis才能找到并加载这些Mapper接口及其对应的XML文件。
在Service层调用:最后,在你的Service层中,你可以像调用普通Java方法一样调用Mapper接口中的方法,MyBatis会自动将调用转发到对应的SQL语句并执行。
mapper namespace
在MyBatis中是一个标识符,用于唯一标识一个Mapper接口。它通常设置为Mapper接口的全限定名(即包含包名的类名)。例如,如果你的Mapper接口路径位于com.example.mp.repository.mapper.StudentMapper
,那么mapper namespace
就应该是"com.example.mp.repository.mapper.StudentMapper"
。
resultType
是MyBatis中用于指定SQL查询返回结果应该被映射到的Java类型的别名或全限定名。它并不直接对应于项目中的一个层或包,而是与你的Java模型(Model)类相关。在例子中,resultType="om.example.mp.model.Student"
表示查询结果应该被映射到om.example.mp.model.Student
类。
其实还有第三个字段parameterType,主要就是SQL入参的类型。比如:
在这个例子中,resultType
被设置为com.example.User
,这意味着查询结果将被映射到User
类的实例中。这里不需要(也不应该)设置parameterType
,因为MyBatis(包括MyBatis-Plus)可以根据方法参数自动推断出它。但是,如果出于某种原因你想显式地指定它,你可以这样做(尽管这在这个特定例子中是多余的):
对于单个基本类型参数(如int
、long
、String
等),MyBatis能够自动处理,因此显式指定parameterType
通常是不必要的。
package com.example.mp.service; import com.example.mp.model.Student; import com.example.mp.repository.mapper.StudentMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentService { @Autowired private StudentMapper studentMapper; public void saveStudent(Student student) { // 检查必要属性是否为空 if (student.getName() != null && student.getAge() > 0) { // 执行插入操作 studentMapper.save(student); System.out.println("学生信息插入成功"); } else { System.out.println("学生信息插入失败,缺少必要属性"); } } }
package com.example.mp.controller; import com.example.mp.model.Student; import com.example.mp.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/students") public class StudentController { @Autowired private StudentService studentService; @PostMapping public String addStudent(@RequestBody Student student) { studentService.saveStudent(student); return "Student added successfully"; } @GetMapping public String addStudent(long id,String name,int age) { Student student = new Student(); student.setId(id); student.setName(name); student.setAge(age); studentService.saveStudent(student); return "Student added successfully"; } }
分别用get,post,body和参数的方式做了实验,结果能成功插入数据库。棒棒哒。
但是我们对MP的学习还没有结束。还有个重要课题,就是构造器。
使用构造器方式(Wrapper)是MyBatis Plus提供的一种更灵活的SQL查询方式,它可以帮助你快速构建复杂的查询条件,并生成对应的SQL语句。相比于传统的XML映射文件,使用构造器方式可以减少重复代码,提高代码的可读性和灵活性。
推荐MyBatis-Plus中的Wrapper
(包括QueryWrapper
、UpdateWrapper
、LambdaQueryWrapper
和LambdaUpdateWrapper
)的理由主要有以下几点:
1. 简化复杂查询和更新条件的构建
Wrapper
提供了丰富的链式函数,允许开发者通过链式调用的方式构建复杂的查询和更新条件。这种方式比传统的XML SQL语句或字符串拼接更加直观和易于维护。LambdaQueryWrapper
和LambdaUpdateWrapper
通过Lambda表达式的方式引用实体类的属性名,避免了手写字段名字符串可能带来的拼写错误和不易维护的问题,提高了代码的类型安全性。2. 提高开发效率
Wrapper
可以显著减少重复的代码模板,使得开发者能够更加专注于业务逻辑的实现。Wrapper
的灵活性和易用性可以帮助开发者快速构建查询和更新条件,提高开发效率。3. 易于维护和扩展
Wrapper
的链式调用方式使得代码结构更加清晰,易于理解和维护。Wrapper
提供的灵活条件构建能力使得开发者可以轻松地扩展查询和更新条件,而不需要对原有代码进行大规模修改。4. 安全性
Wrapper
本身并不直接提供防SQL注入的功能,但MyBatis-Plus在内部对SQL语句进行了预处理和参数绑定,这在一定程度上降低了SQL注入的风险。然而,开发者仍然需要确保传递给Wrapper
的参数是安全的,避免将用户输入直接用于构建条件。若要使用Wrapper来快速实现SQL读写,上面的关于Student的Demo代码,我们可以改造如下:
package com.example.application.service; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.example.application.mapper.StudentMapper; import com.example.application.model.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class StudentService { @Autowired private StudentMapper studentMapper; public List findStudentsByName(String name) { QueryWrapper queryWrapper = new QueryWrapper<>(); queryWrapper.eq("name", name); return studentMapper.selectList(queryWrapper); } public void updateStudentAge(Long id, int age) { UpdateWrapper updateWrapper = new UpdateWrapper<>(); updateWrapper.eq("id", id).set("age", age); studentMapper.update(null, updateWrapper); } }
package com.example.application.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.application.model.Student; public interface StudentMapper extends BaseMapper { }
在上面的示例中, StudentService
中的 findStudentsByName
方法使用 QueryWrapper
构造器来构建查询条件,实现根据学生姓名查询学生信息; updateStudentAge
方法使用 UpdateWrapper
构造器来构建更新条件,实现根据学生ID更新学生年龄的操作。
selectList
和 update
方法是基于MyBatis Plus提供的 BaseMapper
接口而来,不需要在Mapper接口中显式定义。
通过使用Wrapper,可以简化SQL查询条件的构建,提高代码的可维护性和可读性。
PS:尽管见识了MP的构造器Wrapper的灵巧和强大,但是我个人而言,潜意识还是很抗拒摆脱SQL的写法,不知道你怎么想?
好了,先到这里,下次《菜鸟从0学微服务》再见!