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

被折叠的 条评论
为什么被折叠?



