MyBatis入坑:There is no getter for property named ‘xxx’ in ‘class Java.lang.Integer’
1. 问题描述
在配置MyBatis的Mapper映射器时,使用到:
<select id="findUserById" parameterType="Integer" resultType="user"> SELECT * FROM user <where> <if test="id != null and id != 0"> id = #{id} </if> </where> </select>接口方法:
public User findUserById(Integer id);时候就会出现如下错误:
org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'id' in 'class java.lang.Integer' ### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'id' in 'class java.lang.Integer'
2. 问题分析
可见:在配置findUserById时候,参数类型为Integer,为Java中的普通类型,而id又是属于自定义的User实体类中的属性。很明显,在Integer类型中并不存在id属性。所以会报错。
3. 问题解决
3.1. 第一种解决方法:
修改接口参数:
原来:
public User findUserById(Integer id);修改为:
public User findUserById(@Param(value = "id") Integer id);将id由注解Param指定。这样在参数指定中就有了id参数,就可以被if test捕捉得到。
3.2. 第二种解决方法:
修改配置: 将参数名id改为_parameter
原来:
<select id="findUserById" parameterType="Integer" resultType="user"> SELECT * FROM user <where> <if test="id != null and id != 0"> id = #{id} </if> </where> </select>修改为:
<select id="findUserById" parameterType="Integer" resultType="user"> SELECT * FROM user <where> <if test="_parameter != null and _parameter != 0"> id = #{id} </if> </where> </select>
1049

被折叠的 条评论
为什么被折叠?



