溫馨提示×

MyBatisPlus動態(tài)SQL如何配置

小樊
88
2024-07-13 15:42:26
欄目: 云計算

MyBatisPlus(簡稱MP)是基于MyBatis的增強(qiáng)工具,在使用動態(tài)SQL時,配置方式與MyBatis并無太大差異,只是在實(shí)現(xiàn)方式上做了一些簡化和優(yōu)化。下面是MyBatisPlus動態(tài)SQL的配置方式:

  1. 在實(shí)體類(Entity)中使用注解@TableField來標(biāo)識字段
public class User {
    @TableId
    private Long id;
    
    @TableField
    private String username;
    
    @TableField
    private Integer age;
}
  1. 在Mapper接口中使用注解@Mapper或者在啟動類中添加@MapperScan注解來掃描Mapper接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
    // 自定義SQL方法
}
  1. 在XML文件中拼接動態(tài)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>
  1. 在Service層調(diào)用Mapper接口的方法
@Service
public 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);
    }
}

通過以上配置,可以實(shí)現(xiàn)動態(tài)SQL的拼接和執(zhí)行。MyBatisPlus提供了更加便捷的操作數(shù)據(jù)庫的方式,可以大大提高開發(fā)效率。

0