子查询:

同表中子查询直接在statement中写,和sql格式一样;

不同表间的子查询通过resultMap来实现:

<resultMap type = "Book" id = "BookAndReader" autoMapping = "true">
    <id colume = "id" property = "id"/>
    <association property = "reader" javaType = "Reader" autoMapping = "true" select = "queryReaderById" column = "reader_id">
        <!--select进行子查询声明,其参数为子查询语句ID-->
        <!--column为子查询参数,即从pojo类传过来的#{id}-->
    </association>
</resultMap>
<select id = "queryBookAll" resultMap = "BookAndReader">
    select * from book where book_number = #{number}
</select>
<select id = "queryReaderById" resultType = "Reader">
    <!--这里是子查询实体-->
    select * from reader where reader_id = #{id}
</select>

这里和SQL语句一样,先执行子查询,resuktMap在主查询执行之前就存在了,xml文件读取过程中不执行,全部读取完后在数据库中执行,其中子查询得到结果集reader,执行主查询后将结果集返回至resultMap,将其中的子对象与子查询结果集进行关联,排除对不上的,得到最终结果

更多推荐

Mybatis 子查询