当在查询的时候需要传入多个参数的时候该怎么办呢:
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定义: HashMapmap=new HashMap (); 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 HashMapmap=new HashMap (); 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>