一对一查询,使用<association property="***" column="***" select="***"/>查询关联信息时,可能执行报错,
错误信息如下:
org.apache.ibatis.reflection.ReflectionException: There is no setter for property named 'id' in 'class java.lang.String'
说明:
遇到这个错,需要看我们代码中使用的是哪种方式,然后对应核实,
主要区别在于association里面column的传值方式:(1:column="**",2:column="{*=*,*=*}"),以及关联sql中是否指定了参数类型。
接下来列举方式:
假设我们有2个实体,Student和School ,其中Student中关联了School,我们需要查询学生信息,及其对应的学校信息:
com.test.dao.StudentMapper.xml
<resultMap id="StuMap" type="com.test.po.Student">
<id column="id" property="id" />
<result column="stu_name" property="stuName" />
<!-- 方式A:单个参数模式,引用com.test.dao.SchoolMapper.xml查询学校 -->
<association property="schoolA" column="school_id" select="com.test.dao.SchoolMapper.selectSchoolById"/>
<!-- 方式B:单个参数模式,直接使用当前xml查询学校 -->
<association property="schoolB" column="school_id" select="selectSchoolById"/>
<!-- 方式C:多个参数模式,引用com.test.dao.SchoolMapper.xml查询学校 -->
<association property="schoolC" column="{id=school_id}" select="com.test.dao.SchoolMapper.selectSchoolById"/>
<!-- 方式D:多个参数模式,直接使用当前xml查询学校 -->
<association property="schoolD" column="{id=school_id}" select="selectSchoolById"/>
</resultMap>
<select id="getStuById" parameterType="java.lang.String" resultType="com.test.po.Student">
SELECT id, stu_name,school_id FROM t_student WHERE id = #{id}
</select>
com.test.dao.SchoolMapper.xml
<select id="selectSchoolById" parameterType="java.lang.String" resultType="com.test.po.School">
SELECT id, school_name schoolName FROM t_school WHERE id = #{id}
</select>
StudentMapper.xml代码中有方式A/B/C/D,注意:
方式A:
要求在com.test.dao.SchoolMapper.xml中有一个id=“selectSchoolById”的sql,能使用parameterType="java.lang.String"
方式B:
要求在当前xml中有一个id=“selectSchoolById”的sql,能使用parameterType="java.lang.String"
方式C:
要求在com.test.dao.SchoolMapper.xml中有一个id=“selectSchoolById”的sql,不能使用parameterType="java.lang.String"
方式D:
要求在当前xml中有一个id=“selectSchoolById”的sql,不能使用parameterType="java.lang.String"
总结:
1.当使用<association property="***" column="school_Id" select="sqlOther"/>的方式时候,sqlOther里面可以指定参数类型,也可以不指定参数类型
2.当使用<association property="***" column="{id=school_id}" select="sqlOther"/>的方式时候,sqlOther里面不能指定参数类型