请看问题描述
首先我的数据表
对应的类:
user类
Pet类
mapper文件
xml文件
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.PetMapper">
<resultMap id="queryPetByUserIdMap" type="Pet">
<id property="id" column="id"/>
<result property="nickname" column="nickname"/>
<association property="user" column="user_id" select="com.mybatis.mapper.UserMapper.queryUserById"/>
</resultMap>
<select id="queryPetByUserId" resultMap="queryPetByUserIdMap">
select * from mybatis_pet where user_id=#{id}
</select>
</mapper>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.UserMapper">
<resultMap id="queryUserByIdMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="pets" column="id" ofType="Pet" select="com.mybatis.mapper.PetMapper.queryPetByUserId"/>
</resultMap>
<select id="queryUserById" resultMap="queryUserByIdMap" >
select * from mybatis_user where id=#{id}
</select>
</mapper>
测试代码
@Test
public void test1(){
User user = userMapper.queryUserById(1);
System.out.println(user.getId()+"==="+user.getName());
List<Pet> pets = user.getPets();
for (Pet pet : pets) {
System.out.println("================================");
System.out.println(pet.getId()+"==="+pet.getNickname()+"===");
}
}
运行结果
疑问:当我调用userMapper.queryUserById方法的时候,会执行xml文件的sql语句,但因为有resultMap,会执行PetMapper.queryPetByUserId(),但是在PetMapper.Xml文件里面有association,又会继续调用UserMapper.queryUserById方法,而在这个queryUserById方法里面,又继续调用PetMapper.queryPetByUserId(),反反复复查询下去,不就是死循环吗?但是为什么运行的结果却不会出现栈溢出呢?同时我再debug的时候的结果是层层嵌套对象的,按理来说应该是递归的结果导致的才对。而且能正常运行出来!!