数据库一对多查询

环境搭建

实体类:

@Data
public class Teacher {
    
    
    private int id;
    private String name;

    private List<Student> students;
}
@Data
public class Student {
    
    
    private int id;
    private String name;

    //学生需要关联一个老师
    private int tid;
}

按照结果嵌套处理:

<select id="getTeacher" resultMap="getTeacherStudent">
    select s.id sid,s.name sname,t.name tname,t.id tid,s.tid
    from student s ,teacher t
    where s.tid = t.id;
</select>

<!--        复杂的属性需要单独处理  对象association  集合collection
            Javatype=""  指定属性类型!
            集合中的泛型信息使用ofType获取
-->

    <resultMap id="getTeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>

        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="stid"/>
        </collection>

    </resultMap>

按照查询嵌套处理:

  <resultMap id="getTeacherStudent2" type="Teacher">

        <collection property="students" column="id"  javaType="ArrayList" ofType="Student" select="getStudent"/>
    </resultMap>

    <select id="getTeacher2" resultMap="getTeacherStudent2">
        select * from teacher
    </select>

    <select id="getStudent" resultType="Student">
        select * from student
    </select>

小结:
1.关联 - association 多对一
2.集合 - collection 一对多

3.javaType & ofType:
javaType 用来指定实体类中属性的类型
ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

注意点:
保证SQL的可读性,尽量保证通俗易懂
注意一对多和多对一中,属性名和字段的问题
如果问题不好排查错误,可以使用日志,建议使用Log4j

猜你喜欢

转载自blog.csdn.net/weixin_47620760/article/details/114452010