在MyBatis中,可以使用Result注解來實現動態SQL的條件判斷。要使用Result注解,首先需要使用@Select注解來指定查詢的SQL語句,例如:
@Select("SELECT * FROM users")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "email", column = "email"),
@Result(property = "age", column = "age")
})
List<User> findAllUsers();
在@Results注解中,我們可以使用@Result注解來指定屬性和列的映射關系。在動態SQL中,可以使用if屬性來進行條件判斷,例如:
@Select("SELECT * FROM users WHERE 1=1"
+ "<if test=\"username != null\">AND username = #{username}</if>"
+ "<if test=\"email != null\">AND email = #{email}</if>")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "email", column = "email"),
@Result(property = "age", column = "age")
})
List<User> findUsersByCondition(User user);
在上面的例子中,我們使用if屬性來判斷條件是否成立,如果條件成立,則將對應的條件拼接到SQL語句中。這樣就可以實現動態SQL的條件判斷。