mybatis-plus在xml中 根据对象中的某个字段来进行模糊查询
时间: 2024-03-12 20:47:50 浏览: 39
可以使用MyBatis-Plus提供的Wrapper来构建查询条件,具体操作如下:
1. 在Mapper.xml文件中编写SQL语句,使用MyBatis-Plus提供的where标签
```xml
<select id="selectByField" resultType="com.example.demo.entity.User">
select * from user
<where>
<if test="field != null and field != ''">
and name like concat('%',#{field},'%')
</if>
</where>
</select>
```
2. 在对应的Mapper接口中定义方法,并使用@Param注解指定参数名
```java
public interface UserMapper extends BaseMapper<User> {
List<User> selectByField(@Param("field") String field);
}
```
3. 在Service层中调用Mapper方法进行查询
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> selectByField(String field) {
return userMapper.selectByField(field);
}
}
```
4. 在Controller层中调用Service方法进行查询
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/search")
public List<User> search(@RequestParam("field") String field) {
return userService.selectByField(field);
}
}
```
以上代码中,假设User实体类中有一个名为name的字段,需要根据该字段进行模糊查询。在Mapper.xml中使用where标签和if标签构建查询条件,判断field参数是否为空,如果不为空,则拼接like语句。在Mapper接口中定义selectByField方法,并使用@Param注解指定参数名。在Service层中调用Mapper方法进行查询,在Controller层中调用Service方法获取查询结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)