参数传递
单个字面量类型的参数
在mapper接口中使用单个参数,直接使用#{}或者${}在映射文件中接收,注意${}本质是字符串拼接,因此在接收字符型的数据使用单引号括起来,#{}本质为占位符.
eg:
mapper接口:
package com.mappers; import com.pojo.User; public interface UserMapper { User selectUserById(int userid); User selectUserByName(String username); }
映射文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--第一个一致,对应Mapper接口--> <mapper namespace="com.mappers.UserMapper"> <!--第二个一致,对应方法名 User selectUserById(int userid); --> <select id="selectUserById" resultType="user"> select * from user where userid=#{userid} </select> <!--User selectUserByName(String username);--> <select id="selectUserByName" resultType="User"> select * from user where username='${username}' </select> <!-- select * from user where username=#{username}--> </mapper>
调用方法时直接传参:
selectUserByName("张三");
selectUserById(2);
接口方法参数有多个
这时系统会将参数放入Map集合中,以两种方式进行存储
- 以arg0,arg1....为键,传入的参数为值
- 以param1,param2...为键,传入的参数为值
因此在映射文件中访问可以通过#{}或者${}写入对应键进行访问
mapper接口:
package com.mappers; import com.pojo.User; public interface UserMapper { User selectUserByIdAndName(int userid,String username); }
映射文件:
<!-- User selectUserByIdAndName(int userid,String username);--> <select id="selectUserByIdAndName" resultType="User"> select * from user where userid=#{arg0} and username=#{arg1} <!--或者 select * from user where userid=#{param1} and username=#{param2}--> </select>
方式2:
使用map作为参数进行传递多个参数
mapper接口:
package com.mappers; import com.pojo.User; import java.util.Map; public interface UserMapper { User selectUserByIdAndName(Map<String, Object> map); }
映射文件:
<select id="selectUserByIdAndName" resultType="User"> select * from user where userid=#{userid} and username=#{username} </select>
调用:先定义好map,再进行调用
Map<String,Object> map=new HashMap<>(); map.put("userid",2); map.put("username","李四"); User user3=userMapper.selectUserByIdAndName(map);
方式3:(推荐)
使用@Param("")注解,本质也是放到Map集合里,知识我们规定了键名,在使用时直接通过指定的键名访问,在注解的参数里写入我们指定的键名
mapper接口:
package com.mappers; import com.pojo.User; public interface UserMapper { User selectUserByIdAndName(@Param("userid") int userid, @Param("username") String username); }
映射文件:
<select id="selectUserByIdAndName" resultType="User"> select * from user where userid=#{userid} and username=#{username} </select>
传入参数为实体类对象
直接通过#{}或${}和属性名对各个属性值进行使用
mapper接口
package com.mappers; import com.pojo.User; public interface UserMapper { int insertUser(User user); }
映射文件:使用时通过类内属性名即可访问
<!-- int insertUser(User user);--> <insert id="insertUser"> insert into user values (null,#{username},#{userpass},#{usertel},#{usercard}); </insert>
调用:先定义,然后传入使用
User user4=new User(1,"哈哈","aiw","159",10); userMapper.insertUser(user4);