Mybatis传多个参数的五个方法
一、实体类+@Param注解传参(难点,重点,基本会这个就行了)
在我们拥有多个参数的时候,怎么让传入xml文件的参数,选中我们需要的实体类部分,就需要加入@Param注解,在xml中使用注解里面的值,如下面代码,我在@Param中加入了
competitionVo
就需要在xml中,点出来,如competitionVo.singerName
和#{competitionVo.singerName}
Mapper
Page<Competition> competitionInfoPart(Page page,@Param("competitionVo") CompetitionVo competitionVo);
Mapper.xml(不需要看我的SQL,主要理解@Param注解+实体类的使用)
<select id="competitionInfoPart" resultMap="info" parameterType="com.zhao.pojo.CompetitionVo">
select c.*,
s1.singer_name singer1Name,s2.singer_name singer2Name
FROM competition c
INNER JOIN singer s1 on c.singer1_id=s1.singer_id
INNER JOIN singer s2 on c.singer2_id=s2.singer_id
where c.deleted = 0
<if test="competitionVo.singerName!=null">
and (s1.singer_name like CONCAT('%',#{competitionVo.singerName},'%') or s2.singer_name like CONCAT('%',#{competitionVo.singerName},'%'))
</if>
<if test="competitionVo.song!=null">
and (c.singer2_song like CONCAT('%',#{competitionVo.song},'%') or c.singer1_song like CONCAT('%',#{competitionVo.song},'%') )
</if>
<if test="competitionVo.status!=null">
and (c.competition_state = #{competitionVo.status} or c.competition_state = #{competitionVo.status})
</if>
order by c.competition_id desc
</select>
二、实体类传参(重点,经常使用)
Mapper
User selectUser(User user);
Mapper.xml
<select id="selectUser" parameterType="com.zhao.User" resultType="com.zhao.User">
select * from user
where user_name = #{userName} and id = #{id}
</select>
三、@Param传参(重点)
基本类型(int、String…)这样的不需要写 parameterType 写也可以
Mapper
User selectUser(@Param("userName") String name, @Param("id") int id);
Mapper.xml
<select id="selectUser" resultType="com.zhao.User">
select * from user
where user_name = #{userName} and id = #{id}
</select>
四、顺序传参(不建议)
Mapper
User selectUser(String name, int id);
Mapper.xml
<select id="selectUser" resultType="com.zhao.User">
select * from user
where user_name = #{name} and id = #{id}
</select>
五、Map传参(不常用)
Mapper
User selectUser(Map<String, Object> user);
Mapper.xml
<select id="selectUser" parameterType="Map" resultType="com.zhao.User">
select * from user
where user_name = #{name} and id = #{id}
</select>
解决BindingException: Parameter ‘name‘ not found. Available parameters are [xxxx, param1, param2]