MyBatis4——一对一、一对多关联查询

关联查询:
一对一:
1、业务扩展类
    核心:用resultType指定的类的属性包含多表查询的所有字段。
2、resultMap
    通过添加属性成员建立两个类之间的连接
<!--利用resultMap实现一对一  -->
    <select id="queryPersonsByReOnetoOne" parameterType="int" resultMap="person-card-map">
        select p.*,c.* from person p inner join personcard c
        on p.cardid=c.cardid
        where p.id=#{id}
    </select>
    
    <!-- resultMap实现映射 -->
    <resultMap type="person" id="person-card-map">
        <!-- person信息 -->
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="age" column="age"/>
        <!--一对一时,对象成员使用assocation实现映射,javaType指定该属性的类型  -->
        < association property="card" javaType="PersonCard">
            <id property="cardid" column="cardid"/>
            <result property="cardinfo" column="cardinfo"/>
        </association>
    </resultMap>
 
一对多:
<!-- 一对多关联查询  -->
    <select id="queryClassAndPersons" parameterType="int" resultMap="class-person-map">
        select c.*,p.* from person p
        inner join class c
        on c.classid=p.classid
        where c.classid=#{classid}
    </select>
    
    <!-- 类和表的对应关系 -->
    <resultMap type="class" id="class-person-map">
        <!-- 先配class -->
        <id property="classid" column="classid" />
        <result  property="classname" column="classname" />
        <!-- 配置成员属性。属性类型:jdbcType;属性的元素类型:ofType -->
        < collection property="persons" ofType="Person">
            <id property="id" column="id"/>
            <result property="name" column="name"/>
            <result property="age" column="age"/>
        </collection>
    </resultMap>
   

猜你喜欢

转载自www.cnblogs.com/ghlz/p/12234351.html