Mybatis中如何优雅的接收DAO传递的参数

Mybatis中如何优雅的接收DAO传递的参数:

 

1.当dao中传递单个或者多个参数时, 使用@Param(可以类比为别名)注解单一属性

  dao示例:

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

  xml文件示例:

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

如果没有使用@Param注解之后,xml如何获取参数

dao示例:

 User selectUser(String name, int deptId);

xml文件示例:

<select id="demo" resultMap="User">
		select *
			from user where user_id=#{param0} and name= #{param1}
	</select>

 

2.当dao中传递是一个数据实体时,直接在xml中通过属性名获取数据即可

public User selectUser(User user);

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

parameterType:标明参数类型

resultMap:返回结果集

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

 

3.当dao中传递是一个map时,直接在xml中通过key获取数据即可

dao示例:

 List<AttrGroupEntity> selectPageByCatelogId(Map<String, Object> params);

xml示例:

 <select id="selectPageByCatelogId" resultMap="attrGroupMap" parameterType="Map">
        SELECT * FROM pms_attr_group
        <where>
            <if test="catelogId!=null and catelogId !=''">
                catelog_id = #{catelogId}
            </if>
            <if test="key!=null and key != ''">
                AND attr_group_id LIKE CONCAT('%', #{key},'%')
                OR  attr_group_name LIKE CONCAT('%',#{key},'%')
            </if>
        </where>
    </select>

4.当dao中传递是一个list时,直接在xml中遍历list

dao示例:

  boolean deleteAttrGroupByIds(List<Long> longs);

xml示例:

 <delete id="deleteAttrGroupByIds" parameterType="java.util.List" >
        DELETE  FROM pms_attr_group WHERE  attr_group_id IN
        <foreach collection="list" open="(" item="id" close=")" index="index" separator=",">
            ${id}
        </foreach>
       
    </delete>

collection :collection属性的值有三个分别是list、array、map三种,分别对应的参数类型为:List、数组、map集合,我在上面传的参数为数组,所以值为list
    item : 表示在迭代过程中每一个元素的别名
    index :表示在迭代过程中每次迭代到的位置(下标)
    open :前缀
    close :后缀
    separator :分隔符,表示迭代时每个元素之间以什么分隔

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值