不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2022-08-12 13:10:57  修改时间:2024-04-13 07:53:16  分类:Java框架/系统  编辑

1、顺序传参

Dao方法:

public User selectUser(String name, int deptId);

Xml文件:

<select id="selectUser" resultMap="UserResultMap">
    select * from user
    where user_name = #{0} and dept_id = #{1}
</select>

#{}里面的数字代表你传入参数的顺序。

这种方法不建议使用,sql层表达不直观,且一旦顺序调整容易出错。

2、@Param注解传参法

Dao方法:

public User selectUser(@Param("name") String name, @Param("deptId") int deptId);

Xml文件:

<select id="selectUser" resultMap="UserResultMap">
    select * from user
    where user_name = #{name} and dept_id = #{depId}
</select>

#{}里面的名称对应的是注解@Param括号里面修饰的名称。

这种方法在参数不多的情况还是比较直观的,推荐使用。

3、Map传参法

Dao方法:

public User selectUser(Map<String, Object> params);

Xml文件:

<select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>

也可以

<select id="selectUser" parameterType="java.util.Map" resultMap="UserResultMap">
    select * from user
    where user_name = #{params.userName} and dept_id = #{params.deptId}
</select>

#{}里面的名称对应的是Map里面的key名称。

这种方法适合传递多个参数,且 参数易变、能灵活传递的情况。

注意:

MyBatis传递map参数时,如果传递参数中没有对应的key值,在执行sql语句时默认取的是null

例如:map中没有put “name”这个key,在sql中使用#{name}时,默认赋值null

4、实体类 传参法 

Dao方法:

public User selectUser(User params);

Xml文件:

<select id="selectUser" parameterType="com.test.User" resultMap="UserResultMap">
    select * from user
    where user_name = #{userName} and dept_id = #{deptId}
</select>

#{}里面的名称对应的是User类里面的成员属性。

Mybatis会根据#{}中传入的数据,加工成getXxx()方法,通过反射在实体类对象中调用这个方法,从而获取到对应的数据。填充到#{}这个位置。

这种方法很直观,但需要建一个实体类,扩展不容易,需要加属性,看情况使用。

5、实体类+@Param注解传参 —— 个人更倾向于这种 @Param 的用法

在我们拥有多个参数的时候,怎么让传入xml文件的参数,选中我们需要的实体类部分,就需要加入@Param注解,在xml中使用注解里面的值,如下面代码,我在@Param中加入了competitionVo就需要在xml中,点出来,如competitionVo.singerName#{competitionVo.singerName}

Dao方法:

Page<Competition> competitionInfoPart(Page page, @Param("competitionVo") CompetitionVo competitionVo);

Xml文件:

<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>

 

 

参考:

  1. Mybatis实现传入多个参数(实体类型和基本类型)的方法
  2. MyBatis 传递多个参数的4种方式
  3. Mybatis传多个参数的5个方法