MyBatis模糊查詢可以通過(guò)使用 %
或 _
來(lái)實(shí)現(xiàn)。%
表示任意多個(gè)字符(包括0個(gè)字符),_
表示任意一個(gè)字符。
以下是兩種常見(jiàn)的模糊查詢方式:
%
或 _
:<select id="searchUserByName" parameterType="String" resultType="User">
SELECT * FROM user WHERE name LIKE CONCAT('%', #{name}, '%')
</select>
在這個(gè)例子中,查詢語(yǔ)句中的 LIKE CONCAT('%', #{name}, '%')
部分使用了 %
實(shí)現(xiàn)了模糊查詢。
%
或 _
:public List<User> searchUserByName(String name) {
name = "%" + name + "%";
return sqlSession.selectList("searchUserByName", name);
}
在這個(gè)例子中,Java代碼中的字符串拼接操作 name = "%" + name + "%"
實(shí)現(xiàn)了模糊查詢。
這兩種方式都可以實(shí)現(xiàn)模糊查詢,具體使用哪種方式取決于你的需求和個(gè)人偏好。