1. 程式人生 > >mapper對映檔案中parameterType是多個如何傳參

mapper對映檔案中parameterType是多個如何傳參

當在查詢的時候需要傳入多個引數的時候該怎麼辦呢:

1,封裝成一個Model物件,底層HashMap還是一個

複製程式碼
User user=new User();

user.setUserName("zhangsan");

user.setPassword("123456");

queryUserByuserNameAndPass(user);//為返回值型別為User
複製程式碼
<select id="queryUserByuserNameAndPass"  resultType="User" parameterType="com.j1.User"  >

       select * from user
u where u.user_name=#{userName} and u.pass_word=#{passWord} </select>

2,使用HashMap封裝

複製程式碼
//使用HashMap定義:

HashMap <String,Object> map=new HashMap<String,Object>();

map.put("userName","zhangsan");

map.put("password","123456");

queryUserByuserNameAndPass(map);//為返回值型別為User
複製程式碼

//sql 如下:

<select id=
"queryUserByuserNameAndPass" resultType="User" parameterType="Map" > select * from user u where u.user_name=#{userName} and u.pass_word=#{passWord} </select>

3,使用註解,@param

queryUserByuserNameAndPass(@param(''userName")String userName,@param("password")String password)
<select id="queryUserByuserNameAndPass"  resultType=
"User"> select * from user u where u.user_name=#{userName} and u.pass_word=#{passWord}// </select>
queryUserByuserNameAndPass(String userName,String PassWord);  //返回值型別為Usre  

//sql

複製程式碼
<select id="queryUserByuserNameAndPass"  resultType="User">

select * from user u where u.user_name=#{userName} and u.pass_word=#{passWord}//會報錯的

</select>

 
複製程式碼

改為如下:

複製程式碼
<select id="queryUserByuserNameAndPass"  resultType="User">

select * from user u where u.user_name=#{0} and u.pass_word=#{1}//執行成功但是,可讀性不高

</select>

 
複製程式碼

//parameterType 引數型別可以是基本資料型別(int,String,long),可以是Model物件,也可以是Map;

1,基本資料型別:

複製程式碼
//java程式碼

@Override
public void deleteUserById(Long id) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
sqlSession.delete("cn.itcast.mybatis.user.deleteUserById", id);
}
複製程式碼

//sql

<delete id="deleteUserById" parameterType="java.lang.Long">
      DELETE FROM tb_user WHERE id = #{id}
</delete>

2,Model物件

複製程式碼
//java程式碼:

@Override
public void saveUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
sqlSession.insert("cn.itcast.mybatis.user.saveUser", user);
}

@Override
public void updateUser(User user) {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
sqlSession.update("cn.itcast.mybatis.user.updateUser", user);
}
複製程式碼

//sql

複製程式碼
<update id="updateUser" parameterType="cn.itcast.mybatis.pojo.User">
UPDATE tb_user
SET
password = #{password},
name = #{name},
age = #{age},
sex = #{sex},
birthday = #{birthday},
updated = NOW()
WHERE
id = #{id};
</update>
複製程式碼

3.map

複製程式碼
//java

HashMap <String,Object> map=new HashMap<String,Object>();

map.put("userName","zhangsan");

map.put("password","123456");

queryUserByuserNameAndPass(map);//為返回值型別為User
複製程式碼

//sql 如下:

<select id="queryUserByuserNameAndPass"  resultType="User">

select * from user u where u.user_name=#{userName} and u.pass_word=#{passWord}//

</select>