MyBaits传递多个参数

本文详细介绍了在SQL操作中如何根据不同需求传递参数,包括单个参数、多个参数、封装参数以及使用注解的方法,并提供了相应的代码示例。

1.传递一个参数的情况比较容易

比如在mapping.xml中有:

<select id="Find" resultType="ray.bean.User" parameterType="string">
		select * from user where USERNAME=#{username}  
</select>
那么dao层就需要这么调用:(主要是名称和参数类型要正确)

public User Find(String username);
2. 传递多个参数的情况:

(1)、使用map来传递多个参数:

mapping.xml中有:

<!-- 使用map传递多个参数 -->
    <select id="loginUser" resultType="ray.bean.User">
    	select * from user where loginName=#{loginName, jdbcType=VARCHAR} 
    		and password=#{password, jdbcType=VARCHAR} and isAdmin = 1;
    </select>
那么dao中需要这么写:(弊端是在dao接口层不知道参数具体表示什么意思)

public User loginUser(Map<String, String> paramas);
在service层需要这么调:

	public User loginUser(String loginName, String uPwd) {
		Map<String, String> param = new HashMap<String, String>();
		param.put("loginName", loginName);
		param.put("password", uPwd);
		return userDao.loginUser(param);
	}
(2)、通过顺序来调用

<!-- 使用map传递多个参数 -->
    <select id="loginUser" resultType="ray.bean.User">
    	select * from user where loginName=#{0} and password=#{1} and isAdmin = 1;
    </select>
dao层需要这么写:

public User <span style="font-family: Arial, Helvetica, sans-serif;">loginUser </span><span style="font-family: Arial, Helvetica, sans-serif;">(String userName, String passWord);</span>

(3)、通过封装为bean来调(万能的,但是对于较少的参数个数比较麻烦)

<update id="Update" parameterType="ray.bean.User">
		update user set PASSWORD=#{password} where userId=#{userId};
</update>
dao层需要这么写:

public int Update(User user);
(4)、使用注解@param表示参数,是对第一种方法的改进

mapping.xml中:

 <!-- 使用@param传递多个参数 -->
    <select id="loginUser" resultType="ray.bean.User">
    	select * from user where loginName=#{loginName, jdbcType=VARCHAR} 
    		and password=#{password, jdbcType=VARCHAR} and isAdmin = 1;
    </select>
在dao层这么写:

public User loginUser(@Param("userName")String userName, @Param("passWord")String passWord);
service层也不需要封装map











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值