mybatis模糊查詢?cè)趺磳?shí)現(xiàn)

小億
103
2023-09-04 23:38:32

MyBatis模糊查詢可以通過(guò)使用 %_ 來(lái)實(shí)現(xiàn)。% 表示任意多個(gè)字符(包括0個(gè)字符),_ 表示任意一個(gè)字符。

以下是兩種常見(jiàn)的模糊查詢方式:

  1. 在SQL語(yǔ)句中使用 %_
<select id="searchUserByName" parameterType="String" resultType="User">
SELECT * FROM user WHERE name LIKE CONCAT('%', #{name}, '%')
</select>

在這個(gè)例子中,查詢語(yǔ)句中的 LIKE CONCAT('%', #{name}, '%') 部分使用了 % 實(shí)現(xiàn)了模糊查詢。

  1. 在Java代碼中使用 %_
public List<User> searchUserByName(String name) {
name = "%" + name + "%";
return sqlSession.selectList("searchUserByName", name);
}

在這個(gè)例子中,Java代碼中的字符串拼接操作 name = "%" + name + "%" 實(shí)現(xiàn)了模糊查詢。

這兩種方式都可以實(shí)現(xiàn)模糊查詢,具體使用哪種方式取決于你的需求和個(gè)人偏好。

0