When we configure the mapper file, we want to configure the fuzzy query, like this:
<select id="getAllUserRoleDepByName" resultMap="userRoleDepList">
select
u.*,r.*,d.* from
user u left join user_role ur on u.user_id=ur.user_id
left join role r on
r.role_id=ur.role_id
left join department d on
<if test="user_name != null">
u.department_id = d.department_id where u.user_name like '%#{user_name}%'
</if>
</select>
Or like this:
<select id="getAllUserRoleDepByName" resultMap="userRoleDepList">
select
u.*,r.*,d.* from
user u left join user_role ur on u.user_id=ur.user_id
left join role r on
r.role_id=ur.role_id
left join department d on
<if test="user_name != null">
u.department_id = d.department_id where u.user_name like '%' + #{user_name} + '%'
</if>
</select>
I found that it didn't work. I reported an error when I ran it. I also found some methods on the Internet but failed. Finally, I saw the bind method in the dynamic sql on the mybatis official website to solve the problem. The method is as follows:
Define the relevant attributes in bind.
<select id="getAllUserRoleDepByName" resultMap="userRoleDepList">
<bind name="pattern" value="'%' + user_name + '%'"/>
select
u.*,r.*,d.* from
user u left join user_role ur on u.user_id=ur.user_id
left join role r on
r.role_id=ur.role_id
left join department d on
<if test="user_name != null">
u.department_id = d.department_id where u.user_name like #{pattern}
</if>
</select>