mapper對映檔案中parameterType是多個如何傳參
阿新 • • 發佈:2019-02-15
當在查詢的時候需要傳入多個引數的時候該怎麼辦呢:
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 useru 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>