Mybatis 传参的各种姿势,看这一篇就足够,java 使用教程下载
----------------
第二种情况,传入多个参数? userId,sex??使用索引对应值:
注意 mapper 层和 xml 层!
service 层:
@Override
public User getUserInfo(Integer userId,String sex) {
User user = userMapper.getUserInfo(userId,sex);
//省略 业务代码...
return user;
}
mapper 层:
User getUserInfo(Integer userId,String sex);
mapper.xml:
<select id="getUserInfo" resultType="com.demo.elegant.pojo.User">
select userId
from users
where userId=#{0} and sex=#{1};
</select>
--------------------------------------------------------------------------------------
第三种情形,传入多个参数? userId,sex 使用注解 @Param :?
service 层:
@Override
public User getUserInfo(Integer userId,String sex) {
User user = userMapper.getUserInfo(userId,sex);
//省略 业务代码...
return user;
}
mapper 层:
User getUserInfo(@Param("userId")Integer userId,@Param("sex")String sex);
mapper.xml:
<select id="getUserInfo" resultType="com.demo.elegant.pojo.User">
select userId
from users
where userId=#{userId} and sex=#{sex};
</select>
--------------------------------------------------------------------------------------
第四种情形,传入多个参数? ?使用 User 实体类传入,
service 层:
@Override
public User getUserInfo(User user) {
User userInfo = userMapper.getUserInfo(user);
//省略 业务代码...
return userInfo;
}
mapper 层:
User getUserInfo(User User);
mapper.xml:
<select id="getUserInfo" parameterType="User" resultType="com.demo.elegant.pojo.User">
select userId
from users
where userId=#{userId} and sex=#{sex};
</select>
--------------------------------------------------------------------------------------
第五种情形,传入多个参数,?使用 Map 类传入,
service 层:
@Override
public User getUserInfo(Map map) {
User user = userMapper.getUserInfo(map);
//省略 业务代码...
return user;
}
mapper 层:
User getUserInfo(Map map);
mapper.xml 层:
<select id="getUserInfo" parameterType="Map" resultType="com.demo.elegant.pojo.User">
select userId
from users
where userId=#{userId} and sex=#{sex};
</select>?
--------------------------------------------------------------------------------------
第六种情形,传入多个参,使用?map 封装实体类传入**,**
这种情况其实使用场景比较少,因为上面的各种姿势其实已经够用了
service 层:
@Override
public User getUserInfo1(Integer userId,String sex) {
User userInfo = new User(userId,sex);
Map<String,Object> map=new HashMap<String,Object>();
map.put("user",userInfo);
User userResult= userMapper.getUserInfo(map);
//省略 业务代码...
return userResult;
}
mapper 层:?
User getUserInfo(Map map);
mapper.xml:
<select id="getUserInfo" parameterType="Map" resultType="com.demo.elegant.pojo.User">
select userId
from users
where userId=#{userInfo.userId} and sex=#{userInfo.sex};
</select>
--------------------------------------------------------------------------------------
第七种情形,即需要传入实体类,又需要传入多个单独参,使用注解 @Param ,
service 层:
@Override
public User getUserInfo(User user,Integer age) {
User userResult = userMapper.getUserInfo(user,age);
//省略 业务代码...
return userResult;
}
mapper 层:?
User getUserInfo(@Param("userInfo") User user,@Param("age") Integer age);
mapper.xml:
评论