🐳 Mybatis 中的动态查询
一、什么的Mybaits的动态查询
MyBatis 的动态查询是指根据不同的条件来构建 SQL 查询语句。通常使用动态 SQL 不可能是独立的一部分,MyBatis 使用一种强大的动态 SQL 语言来改进这种情形,这种语言可以被用在任意的 SQL 映射语句中。
二、环境搭建
1.新建数据库、 (mybatisdb) 一张表 、 (t_emp)
SQL语句
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_emp
-- ----------------------------
DROP TABLE IF EXISTS `t_emp`;
CREATE TABLE `t_emp` (
`emp_id` int(0) NOT NULL,
`emp_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL,
`emp_salary` decimal(10, 2) NULL DEFAULT NULL,
PRIMARY KEY (`emp_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_emp
-- ----------------------------
INSERT INTO `t_emp` VALUES (1, '名字1', 100.00);
INSERT INTO `t_emp` VALUES (2, '名字2', 200.00);
SET FOREIGN_KEY_CHECKS = 1;
2.添加依赖 (mysql , mybatis , junit , lombok)
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.32</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.10.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
3.新建实体类 Emp
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
private Integer empId ;
private String empName ;
private Double empSalary ;
}
4.新建mapper接口 EmpMapper
public interface EmpMapper {
List<Emp> getEmpListByCondition(Emp emp);
void updateEmp(Emp emp);
List<Emp> getEmpListByCondition2(Emp emp);
List<Emp> getEmpListByCondition3(Emp emp);
List<Emp> getEmpListByCondition4(@Param("empIdList") List<Integer> empIdList);
List<Emp> getEmpList();
}
5.在resources目录下新建com.bottom.mybatis.mapper目录,并新建一个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="com.bottom.mybatis.mapper.EmpMapper">
<!-- 1. where - if -->
<select id="getEmpListByCondition" resultType="Emp">
select * from t_emp
<where>
<if test="empId!=null">
or emp_id = #{empId} <!-- 第9行的empId指的是对象中的属性empId。 or后面的emp_id 表示列名,因为此处是SQL语句部分 , #{}里面的是对象属性名 -->
</if>
<if test="empName!=null">
or emp_name like concat('%',#{empName},'%')
</if>
<if test="empSalary!=null">
or emp_salary < #{empSalary}
</if>
</where>
</select>
<!-- 2. set -->
<update id="updateEmp">
update t_emp
<set>
<if test="empName!=null">
emp_name = #{empName},
</if>
<if test="empSalary!=null">
emp_salary = #{empSalary},
</if>
</set>
where emp_id = #{empId}
</update>
<!-- 3. trim -->
<!-- prefix 表示添加前缀
prefixOverrides 动态的删除指定的前缀单词
suffix 表示添加后缀
suffixOverrides 动态的删除指定的后缀单词
-->
<select id="getEmpListByCondition2" resultType="Emp">
select * from t_emp
<trim prefix="where" prefixOverrides="or|and" suffix=";" suffixOverrides="or|and">
<if test="empId!=null">
emp_id = #{empId} or
</if>
<if test="empName!=null">
emp_name like concat('%',#{empName},'%') or
</if>
<if test="empSalary!=null">
emp_salary < #{empSalary} or
</if>
</trim>
</select>
<!-- 4. choose - when - otherwise -->
<select id="getEmpListByCondition3" resultType="Emp">
select * from t_emp
where
<choose>
<when test="empId!=null">
emp_id=#{empId}
</when>
<when test="empName!=null">
emp_name = #{empName}
</when>
<when test="empSalary!=null">
emp_salary = #{empSalary}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</select>
<!-- 5. foreach -->
<select id="getEmpListByCondition4" resultType="Emp">
<!-- select * from t_emp where emp_id in (1,3,5,7,9) -->
select * from t_emp where emp_id in
<foreach collection="empIdList" separator="," open="(" close=")" item="eid">
#{eid}
</foreach>
</select>
<!-- 6. SQL片段 -->
<sql id="allColumns">
select emp_id as empId , emp_name as empName , emp_salary as empSalary
</sql>
<select id="getEmpList" resultType="Emp">
<include refid="allColumns"/> from t_emp
</select>
</mapper>
6.在 resources 目录下新建 mybatis-config.xml、logback.xml logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<appender name="STDOUT"
class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{HH:mm:ss.SSS}] [%-5level] [%thread] [%logger] [%msg]%n</pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
</root>
<logger name="com.bottom.mybatis" level="DEBUG" />
</configuration>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="SLF4J"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.bottom.mybatis.pojo"/>
</typeAliases>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/relation"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.bottom.mybatis.mapper"/>
</mappers>
</configuration>
1、 where-if
此处的if是动态查询,即输入的条件查询不到结果为空
如果不输入查询条件,默认查询所有
2、trim
在 MyBatis 中,
trim
通常用于对字符串进行修剪操作,去除前后的空格或指定的字符。这可以在映射文件的 SQL 语句中使用,以确保数据的一致性和准确性。
trim
函数的属性如下:
- prefix:在
trim
标签内 SQL 语句加上前缀。 - suffix:在
trim
标签内 SQL 语句加上后缀。 - prefixOverrides:指定去除多余的前缀内容。
- suffixOverrides:指定去除多余的后缀内容。
3、choose-when-otherwise
MyBatis 的
choose-when-otherwise
是条件表达式的一种用法,通常用于在 SQL 映射文件中根据不同的条件执行不同的操作。它允许你根据特定的条件选择不同的逻辑或生成不同的 SQL 语句。
4、foreach
foreach
是用来构建in
条件的,它可以在 SQL 语句中进行迭代一个集合。foreach
有List
、array
、Map
三种类型的使用场景。
5、sql片段
使用
<sql>
标签来定义 SQL 片段。SQL 片段是一段可重用的 SQL 代码块,可以在多个 SQL 语句中引用。SQL 片段的使用可以减少重复编写相同 SQL 代码的工作,提高代码的可维护性和重用性
6、分页插件
分页插件是一种用于在 MyBatis 框架中实现分页功能的插件。它可以帮助开发者在查询大量数据时,将结果分成多个页面显示,从而提高查询的效率和用户体验。
使用分页插件的步骤如下
- 添加依赖:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.0</version>
</dependency>
- 配置分页插件(mybatis-config.xml):
- 在查询功能之前使用
PageHelper.startPage(int pageNum, int pageSize)
开启分页功能。
转载自:https://juejin.cn/post/7351624415316672527