引言
在实际的开发中,经常需要对数据库进行模糊查询操作。而使用mybatis-plus框架,可以以更简洁的方式完成这些操作。本文将介绍如何使用mybatis-plus的构造器来实现String集合拼多个or的模糊查询。
问题描述
我们假设有一个User表,包含id和name两个字段,我们需要根据一组关键字对name字段进行模糊查询。
实现步骤
1. 添加依赖
在pom.xml文件中添加mybatis-plus的依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
2. 创建实体类
创建User实体类,包含id和name两个字段:
@Data
@TableName("user")
public class User {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField("name")
private String name;
}
3. 创建Mapper接口
创建UserMapper接口,继承BaseMapper,并添加以下方法:
public interface UserMapper extends BaseMapper<User> {
List<User> fuzzyQuery(List<String> keywords);
}
4. 创建Mapper.xml文件
创建UserMapper.xml文件,添加以下SQL语句:
<mapper namespace="com.example.mapper.UserMapper">
<select id="fuzzyQuery" resultType="com.example.entity.User">
SELECT * FROM user WHERE
<foreach collection="keywords" item="keyword" separator="OR">
name LIKE CONCAT('%',#{keyword},'%')
</foreach>
</select>
</mapper>
5. 使用构造器实现模糊查询
在Service层调用Mapper的fuzzyQuery方法,传入关键字列表:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> fuzzyQuery(List<String> keywords) {
return userMapper.fuzzyQuery(keywords);
}
}
6. 测试查询结果
在Controller层进行测试,添加以下代码:
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/fuzzy/{keywords}")
public List<User> fuzzyQuery(@PathVariable List<String> keywords) {
return userService.fuzzyQuery(keywords);
}
}
总结
通过使用mybatis-plus的构造器,我们可以轻松实现String集合拼多个or的模糊查询。只需在Mapper接口中定义对应的方法,并在Mapper.xml文件中编写相应的SQL语句即可。mybatis-plus的简洁的API,大大提高了开发效率。
希望本文能帮助到你,如有任何疑问,请留言讨论。谢谢阅读!
本文来自极简博客,作者:冬日暖阳,转载请注明原文链接:String集合拼多个or,模糊查询。mybatis-plus-构造器的写法
微信扫一扫,打赏作者吧~