Mybatis传递参数实现方式

前言

单个参数

传参的基本方式有两种:#{param} ${param}

#{}为参数占位符?,即SQL预编译 推荐使用
${}为字符串替换,即SQL拼接

多个参数

实体传入

service层:

1
2
3
4
5
@Override
public User getUserInfo(User user) {
User userInfo = userMapper.getUserInfo(user);
return userInfo;
}

mapper层:

1
2
3
4
@Mapper
public interface UserMapper{
User getUserInfo(User User);
}

mapper.xml:

1
2
3
4
5
6

<select id="getUserInfo" parameterType="User" resultType="com.pojo.User">
select userId
from users
where userId=#{userId} and sex=#{sex};
</select>

Map传入

service层:

1
2
3
4
5
@Override
public User getUserInfo(Map map) {
User user = userMapper.getUserInfo(map);
return user;
}

mapper层:

1
2
3
4
@Mapper
public interface UserMapper{
User getUserInfo(Map map);
}

mapper.xml层:

1
2
3
4
5
6
<!--查询-->
<select id="getUserInfo" parameterType="Map" resultType="com.pojo.User">
select userId
from users
where userId=#{userId} and sex=#{sex};
</select>

注解@Param传入

service层:

1
2
3
4
5
@Override
public User getUserInfo(User user,Integer age) {
User userResult = userMapper.getUserInfo(user,age);
return userResult;
}

mapper层:

1
2
3
4
@Mapper
public interface UserMapper{
User getUserInfo(@Param("userInfo") User user,@Param("age") Integer age);
}

mapper.xml:

1
2
3
4
5
6
<!--查询-->
<select id="getUserInfo" resultType="com.pojo.User">
select userId
from users
where userId=#{userInfo.userId} and sex=#{userInfo.sex} and age=#{age};
</select>

参考:


Mybatis传递参数实现方式
https://github.com/i-xiaoxin/2022/09/21/Mybatis传递参数实现方式/
作者
xiaoxinlore
发布于
2022年9月21日
许可协议