Param注解的使用

  本文主要详细介绍一下@Param的使用方法。
  Caused by: org.apache.ibatis.binding.BindingException: Parameter ‘id’ not found. Available parameters are [1, 0, param1, param2]
  在不使用@Param注解的时候,有时候会报上边这个异常,根据此异常进行讲解。

@Param注解在Mybatis中的使用 以及传递参数的三种方式

1.第一种:

Dao层的方法

1
public User selectUser(String name,String password);

对应的Mapper.xml

1
2
3
<select id="selectUser" resultMap="BaseResultMap">  
select * from t_user where user_name = #{0} and user_password=#{1}
</select>

占位符不够直观!

2.第二种:

该方法采用Map传多参数
Dao层的方法

1
public User selectUser(Map paramMap);

对应的Mapper.xml

1
2
3
<select id="selectUser" resultMap="BaseResultMap">  
select * from t_user where user_name = #{userName,jdbcType=VARCHAR} and user_password=#{userPassword,jdbcType=VARCHAR}
</select>

Service层调用

1
2
3
4
5
6
public User xxxSelectUser(){  
Map paramMap=new hashMap();
paramMap.put("userName","对应具体的参数值");
paramMap.put("userPassword","对应具体的参数值");
User user=xxx.selectUser(paramMap);
}

个人认为此方法不够直观,见到接口方法不能直接的知道要传的参数是什么。

3.第三种:

该方法采用@Param注解
Dao层的方法

1
public User selectUser(@Param("name")String name, @Param("password")String password);

对应的Mapper.xml

1
2
3
<select id=" selectUser" resultMap="BaseResultMap">  
select * from t_user where user_name = #{name,jdbcType=VARCHAR} and user_password=#{password,jdbcType=VARCHAR}
</select>

这种可读性最好,建议双引号中的值和变量名保持一致。

4.第四种:

只有一个参数
Dao层的方法

1
public List<student> selectuser(int pn);

对应的Mapper.xml

1
2
3
<select id="selectuser"  resultType="com.user.entity.student">
SELECT * FROM student LIMIT #{page} ,5
</select>

5.第五种:

单个对象接受
定义一个POJO

1
2
3
4
5
6
7
public class User {
private String username;
private String birthday;
private String sex;
private String address;
/*getter和setter*/
}

Dao层的方法

1
public void insertUser(User user) throws Exception;

对应的Mapper.xml

1
2
3
<insert id="insertUser" parameterType="com.itheima.mybatis.po.User">​
INSERT INTO USER (username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})
</insert>

5.第五种:

多个对象接受
Dao层的方法

1
public List<Role> findRoleByMix(@Param("roleP") RoleParam role, @Param("permissionP") PermissionParam permission);

对应的Mapper.xml

1
2
3
4
5
6
<select id="findRoleByMix" resultType="role">
SELECT id,name FROM t_role
WHERE roleName=#{roleP.roleName}
AND note=#{rolep.note}
AND level=#{permissionP.level}
<select>