Mybatis异常:org.apache.ibatis.type.TypeException: Could not set parameters for mapping
往Mybatis的XML层注入参数时报错:
nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping:
ParameterMapping{property='groupClient', mode=IN, javaType=class java.lang.Object, jdbcType=VARCHAR, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}.
Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #1 with JdbcType VARCHAR . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #1 with JdbcType VARCHAR . Try setting a different JdbcType for this parameter or a different configuration property. Cause: org.postgresql.util.PSQLException
这是因为dao层到 mapper.xml参数注入的时候转换异常,造成此类异常原因可能有两种:
1,入参类型不匹配
2,like模糊查询方式不对
1,入参类型不匹配
示例如下:
Mapper.java
List<Student> selectStudent(@Param("name") String name, @Param("age") int age,@Param("id")Long id);
或者
List<Student> selectStudent(Map<String,Object> map);
Mapper.xml
<select id="selectStudent" resultMap="BaseResultMap" parameterType="java.lang.String">
select * from student where name=#{name} and age=#{age} and id=#{id}
</select>
这种情况就会导致此类异常,因为有多种数据类型,而mapper.xml里参数类型只写了一种 parameterType=“java.lang.String”,所以参数注入的时候转换异常,只需要把parameterType去掉即可,如下:
<select id="selectStudent" resultMap="BaseResultMap">
select * from student where name=#{name} and age=#{age} and id=#{id}
</select>
2,like模糊查询方式不对
示例如下:
Mapper.java
List<Student> selectStudent(@Param("name") String name, @Param("age") int age,@Param("id")Long id);
或者
List<Student> selectStudent(Map<String,Object> map);
Mapper.xml
<select id="selectStudent" resultMap="BaseResultMap">
select * from student where name like '%#{name}%' and age=#{age} and id=#{id}
</select>
%#{name}%这种情况就会导致此类异常,因为在Mybatis的XML中直接使用模糊查询会有问题,应该使用CONCAT()函数拼接,如下:
方式一:CONCAT()函数
<select id="selectStudent" resultMap="BaseResultMap">
select * from student where name like CONCAT('%',#{name},'%') and age=#{age} and id=#{id}
</select>
方式二:直接拼接完再传参
在service层直接拼接完再传参:
String roleName = "%" + name+ "%";
studentDao.selectStudent(name, int age, Long id);
方式三:Mybatis的bind
<select id="selectStudent" resultMap="BaseResultMap">
<bind name="keyword" value="'%' + name+ '%'" />
select * from student where name=#{name} and age=#{age} and id=#{id}
</select>
参考文章:
https://blog.csdn.net/weixin_49114503/article/details/135336422
https://blog.csdn.net/jdk_wangtaida/article/details/106126421