1、单个字面量类型的参数
此时可以使用KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{}以任意的名称获取参数的值,…{}需要手动加单引号
<select id="getUserByName" resultType="com.lucky.pojo.User">
<!--select * from t_user where username=#{username}-->
<!--select * from t_user where username=#{eee}-->
select * from t_user where username= '${eee}'
</select>
如果使用 ,必须 加 ′ ′ ,不然 M y b a t i s 会将参数解析为列名。因为 , 必须加'', 不然Mybatis会将参数解析为列名。因为 ,必须加′′,不然Mybatis会将参数解析为列名。因为的本质是字符串拼接。#的本质是占位符。
2、多个字面量类型的参数
mapper接口中的方法,有两个参数
User checkLogin(String name, String password);
如果在映射文件中直接使用参数名称
<select id="checkLogin" resultType="com.lucky.pojo.User">
select * from t_user where username= #{username} and password= #{password}
</select>
这时候会报错,参数username不可用,可用参数为 [arg1, arg0, param1, param2]
因此映射文件中,sql语句的正确写法为:
<select id="checkLogin" resultType="com.lucky.pojo.User">
select * from t_user where username= #{param1} and password= #{param2}
</select>
当方法有多个输入参数时,此时MyBatis会自动将这些参数放在一个map集合中,以arg0,arg1…为键,以参数为值;以param1,param2…为键,以参数为值;因此只需要通过${}和#{}访问map集合的键就可以获取相对应的参数取值。
3、Map类型参数
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中。
查询方法定义
User checkLogin2(Map<String, String> params);
映射文件sql写法
<select id="checkLogin2" resultType="com.lucky.pojo.User">
select * from t_user where username= #{username} and password= #{password}
</select>
4、实体类型参数
若mapper接口中的方法参数为实体类对象时
此时可以使用KaTeX parse error: Expected 'EOF', got '#' at position 4: {}和#̲{},通过访问实体类对象中的属…{}需要手动加单引号。
mapper方法定义
int insertUser(User user);
映射文件sql定义
<insert id="insertUser">
insert into t_user values(null,#{username}, #{password}, #{age}, #{gender}, #{email})
</insert>
5、使用@Param标识参数
mapper中方法定义时,给参数加上@param注解,注解参数为xml文件中使用的参数名称
User checkLogin3(@Param("name") String name, @Param("pwd") String password);
xml文件中sql语句定义
<select id="checkLogin3" resultType="com.lucky.pojo.User">
select * from t_user where username= #{name} and password= #{pwd}
</select>