Mybatis六种传参方式
顺序传参
Mapper代码
User getUserByParam(String phone, String password);
xml代码
<select id="getUserByParam" resultType="com.example.demo.model.User">
select `user_id`,`real_name`,`nick_name`,`sex`,`phone`,`password` from bss_user
where `phone` = #{param1} and `password` = #{param2}
</select>
使用@Param
传参
-
@Param
为该参数属性赋予key
值
- 如果1-4个参数使用该方式,超过推荐map或实体类
mapper代码
User getUserByParam(@Param("key1") String phone, @Param("key2") String password);
xml代码
<select id="getUserByParam" resultType="com.example.demo.model.User">
select `user_id`,`real_name`,`nick_name`,`sex`,`phone`,`password` from bss_user
where `phone` = #{key1} and `password` = #{key2}
</select>
使用Map传参
mapper代码
User getUserByParam(Map<String, Object> params);
xml代码
<select id="getUserByParam" resultType="com.example.demo.model.User">
select `user_id`,`real_name`,`nick_name`,`sex`,`phone`,`password` from bss_user
where `phone` = #{phone} and `password` = #{password}
</select>
使用@Param
和Map组合传参
mapper代码
User getUserByParam(@Param("params") Map<String, Object> params);
xml代码
<select id="getUserByParam" resultType="com.example.demo.model.User">
select `user_id`,`real_name`,`nick_name`,`sex`,`phone`,`password` from bss_user
where `phone` = #{params.phone} and `password` = #{params.password}
</select>
使用实体类传参
mapper代码
User getUserByParam(User user);
xml代码
<select id="getUserByParam" resultType="com.example.demo.model.User">
select `user_id`,`real_name`,`nick_name`,`sex`,`phone`,`password` from bss_user
where `phone` = #{phone} and `password` = #{password}
</select>
List传参
mapper代码
User getUserByParam(List<User> paramList);
xml代码
<select id="getUserByParam" resultType="com.example.demo.model.User">
select `user_id`,`real_name`,`nick_name`,`sex`,`phone`,`password` from bss_user
where
<foreach collection="list" item="item" separator=",">
`phone` = #{item.phone} and `password` = #{item.password}
</foreach>
</select>
网友评论