在Spring Boot中使用MyBatis进行高级查询通常涉及使用复杂的SQL语句、参数映射、结果映射以及可能的动态SQL。MyBatis Plus是MyBatis的增强工具,在MyBatis的基础上提供了许多便利的功能,包括简化CRUD操作、活动记录、代码生成器等。
下面是如何在Spring Boot中使用MyBatis Plus进行高级查询的步骤:
1. 创建Mapper接口
首先,你需要定义一个Mapper接口,用于声明你要执行的高级查询方法。这个接口通常继承自MyBatis Plus提供的BaseMapper<T>
接口,其中T
是你的实体类。这里以自定义的User实体类举例。
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
public interface UserMapper extends BaseMapper<User> {
// 自定义查询方法
List<User> selectByCustomConditions(YourCustomParam param);
}
2. 编写Mapper XML
然后,你需要为自定义的查询方法编写对应的XML映射文件。这个文件应该放在resources/mapper
目录下(或者你在配置文件中指定的其他位置)。
<?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.example.demo.mapper.UserMapper">
<!-- namespace就是空间位置,指向抽象类UserMapper -->
<select id="selectByCustomConditions" resultType="com.example.demo.entity.User">
<!-- id是在UserMapper抽象类里面定义的方法名,resultType是select语句应该返回的数据格式 -->
SELECT * FROM user
WHERE 1 = 1
<if test="name != null">
AND name LIKE CONCAT('%', #{name}, '%')
</if>
<if test="someField != null">
AND some_field = #{someField}
</if>
<if test="param.someField != null">
AND some_field = #{param.someField}
</if>
</select>
</mapper>
在这个XML中,你可以使用MyBatis提供的各种XML标签(如<if>
、<choose>
、<when>
、<otherwise>
等)来编写复杂的SQL逻辑。
模糊查询时,需要用到CONCAT去拼接通配符。
3. 使用Mapper
在你的服务层或控制器中,你可以通过注入UserMapper
来调用你的高级查询方法。
import com.example.demo.mapper.UserMapper;
import com.example.demo.entity.User;
import com.example.demo.param.YourCustomParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> findUsersByCustomConditions(YourCustomParam param) {
return userMapper.selectByCustomConditions(param);
}
}
4. 创建Controller层
创建UserController调用Service层即可(@Autowired private UserService userService)