【MyBatis学习笔记】一对一、一对多关联

一对一关联

1.用业务扩展类实现:

​ 三张表三个实体类 Student StudentCard StudentBusiness(继承多属性的类重写少属性的类)

xml:

<select id="queryStudentByOneToOne" parameterType="int" resultType="StudentBusiness">
    select s.*, s2.* from student s inner join studentcard s2 on s.cid = s2.cid where s.sid = #{sid}
</select>

java.test:

StudentBusiness studentBusiness = studentMapper.queryStudentByOneToOne(4);

2.用resultMap实现:

​ a.通过 属性成员 将2个类建立起联系

xml:

<select id="queryStudentOTOWithResultMap" parameterType="int" resultMap="student_card_map">
    select s.*, s2.* from student s inner join studentcard s2 on s.cid = s2.cid
    where s.sid = #{sid}
</select>

<resultMap id="student_card_map" type="student">
    <id property="sid" column="sid"/>
    <result property="sname" column="sname"/>
    <result property="sage" column="sage"/>
    <result property="sgender" column="sgender"/>
    <result property="gname" column="gname"/>

    <!--
        一对一时,对象成员使用association映射
        javaType指定该属性类型
    -->
    <association property="studentCard" javaType="StudentCard">
        <id property="cid" column="cid"/>
        <result property="cinfo" column="cinfo"/>
    </association>

    <association property="address" javaType="Address">
        <result property="homeAddress" column="homeaddress"/>
        <result property="schoolAddress" column="schooladdress"/>
    </association>
</resultMap>

test.java:

student stu = studentMapper.queryStudentOTOWithResultMap(4);
一对多关联

xml:

select c.*, s.* from class c inner join student s on c.classid = s.classid where c.classid = #{classid}
<resultMap id="class_student_map" type="Class">
    <id property="classid" column="classid"/>
    <result property="classname" column="classname"/>

    <!--
        一对多时,对象成员使用collection映射
        javaType指定该属性类型
        ofType指属性的元素类型
    -->
    <collection property="students" ofType="student">
        <id property="sid" column="sid"/>
        <result property="sname" column="sname"/>
        <result property="sage" column="sage"/>
        <result property="sgender" column="sgender"/>
        <result property="gname" column="gname"/>

        <association property="studentCard" javaType="StudentCard">
            <id property="cid" column="cid"/>
            <result property="cinfo" column="cinfo"/>
        </association>

        <association property="address" javaType="Address">
            <result property="homeAddress" column="homeaddress"/>
            <result property="schoolAddress" column="schooladdress"/>
        </association>
    </collection>
</resultMap>

test.java:

    Class Class = studentMapper.queryClassAndStudent(1);
    List<student> students = Class.getStudents();
    for(student stu : students){
        System.out.println(stu);
    }
    //System.out.println(Class);
发布了46 篇原创文章 · 获赞 1 · 访问量 2406

猜你喜欢

转载自blog.csdn.net/weixin_43708069/article/details/104419954
今日推荐