mybatis one-to-many/many-to-many query is empty

When learning the one-to-many and many-to-many association query of mybatis, because the association relationship has not been added, the foreign key is empty, resulting in an empty return result after the query.
This imitates the relationship between student (student), class (classes) and course selection (stu_cou), when querying a student, the three tables of student table (student), class table (classes) and course selection table (stu_cou) are connected by id , when the selected class schedule is not related to the current student , the query is empty. The
original select configuration is:

    <select id="selectStudent" resultMap="studentMap">
        SELECT s.id as stu_id,s.name as stu_name,classes_id,
                c.id as c_id,c.name as c_name
        FROM student s,stu_cou sc ,classes c on 
        WHERE s.id=#{id}
            and s.id=sc.stu_id 
            and c.id=sc.cou_id
    </select>

Solution:

    <select id="selectStudent" resultMap="studentMap">
        SELECT s.id as stu_id,s.name as stu_name,classes_id,
                c.id as c_id,c.name as c_name
        FROM student s left join stu_cou sc on s.id=sc.stu_id 
                left join classes c on c.id=sc.cou_id
        WHERE s.id=#{id}
    </select>

Connect each table through left join, so that the attributes that do not exist will be automatically set to empty. When the selected class table is not related to the current student , the student object can also be returned.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325636596&siteId=291194637