MyBatis是一個優(yōu)秀的持久層框架,可以通過XML配置文件或者注解方式進(jìn)行SQL語句的編寫和執(zhí)行。在MyBatis中,條件查詢和分頁查詢是經(jīng)常使用的功能,結(jié)合起來可以更靈活地進(jìn)行數(shù)據(jù)查詢。
下面是一個示例代碼,演示了如何在MyBatis中進(jìn)行條件查詢和分頁查詢:
public interface UserMapper {
List<User> findUsersByCondition(@Param("username") String username, @Param("age") Integer age, RowBounds rowBounds);
}
<select id="findUsersByCondition" parameterType="java.util.Map" resultType="User">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
@Autowired
private UserMapper userMapper;
public List<User> findUsersByCondition(String username, Integer age, int offset, int limit) {
RowBounds rowBounds = new RowBounds(offset, limit);
return userMapper.findUsersByCondition(username, age, rowBounds);
}
@RequestMapping("/users")
public List<User> getUsers(@RequestParam(required = false) String username,
@RequestParam(required = false) Integer age,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
int offset = page * size;
return userService.findUsersByCondition(username, age, offset, size);
}
通過以上步驟,我們可以實(shí)現(xiàn)在MyBatis中進(jìn)行條件查詢與分頁查詢的功能。在Mapper XML文件中使用<where>
標(biāo)簽可以動態(tài)拼接查詢條件,在Service層使用RowBounds
對象實(shí)現(xiàn)分頁查詢,在Controller層處理請求參數(shù)并調(diào)用Service層方法獲取數(shù)據(jù)。這樣可以更加靈活地進(jìn)行數(shù)據(jù)查詢操作。