Mybatis一对多返回结果问题

1、xml映射文件解析(在映射文件中做一对多关联查询)classMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mtqg.identify.expertServer.mapper.ClassesMapper">
<!-- 一对多关联,查询数据SQL。是class和student两个表的联合查询 -->
    <select id="getClass3" parameterType="int" resultMap="ClassResultMap3">
        select * from class c, student s where  c.C_id=s.class_id and  c.c_id=#{id}
    </select>
    <!-- 将两个表的数据连接在一起 。id="ClassResultMap3"与上面的resultMap="ClassResultMap3"相对应-->
    <resultMap type="com.mtqg.identify.expertServer.entityDemo.Classes" id="ClassResultMap3">
    <!--此处的column="c_id"一定要与下面 column="s_id"区分开。虽然在数据库中数据两个表的id可以都叫id,但是在mybatis映射文件中更需要做区分 -->
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <!-- ofType指定students集合中的对象类型 -->
        <collection property="students" ofType="com.mtqg.identify.expertServer.entityDemo.Student">
            <id property="id" column="s_id"/>
            <result property="name" column="s_name"/>
        </collection>
    </resultMap>
</mapper>

注意看代码第10行column="c_id"一定要与column="s_id"区分开,不能都叫id。虽然在数据库中数据两个表的id可以都叫id,但在mybatis映射文件中更需要做区分 楼主在这个地方整了半天的时间。因为两个表都用了相同的id,所以只能查出一条数据来,因为看了 http://www.oschina.net/question/154489_141658 。把主键改成不同的名字后才可以的
发布了42 篇原创文章 · 获赞 32 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/m0_37027631/article/details/72868221
今日推荐