MyBatisPlus(简称MP)是基于MyBatis的增强工具,在使用动态SQL时,配置方式与MyBatis并无太大差异,只是在实现方式上做了一些简化和优化。下面是MyBatisPlus动态SQL的配置方式:
在实体类(Entity)中使用注解@TableField来标识字段public class User { @TableId private Long id; @TableField private String username; @TableField private Integer age;}在Mapper接口中使用注解@Mapper或者在启动类中添加@MapperScan注解来扫描Mapper接口@Mapperpublic interface UserMapper extends BaseMapper<User> { // 自定义SQL方法}在XML文件中拼接动态SQL<select id="findUser" resultType="User"> SELECT * FROM user <where> <if test="username != null"> AND username = #{username} </if> <if test="age != null"> AND age = #{age} </if> </where></select>在Service层调用Mapper接口的方法@Servicepublic class UserService { @Autowired private UserMapper userMapper; public List<User> findUser(String username, Integer age) { QueryWrapper<User> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("username", username); queryWrapper.eq("age", age); return userMapper.selectList(queryWrapper); }}通过以上配置,可以实现动态SQL的拼接和执行。MyBatisPlus提供了更加便捷的操作数据库的方式,可以大大提高开发效率。