[MyBatis]—Association mapping of the framework (configuration file method)

I. Overview:

     In actual development, the operation of the database often involves multiple tables, which involves the association between objects in object-oriented. For operations between multiple tables, the MyBatis framework provides association mapping, through which the association between objects can be well handled.

2. Relationship:

       Let's look at two tables, Teacher (teacher table) and Teaching (teaching course table), and then the teacher's job number (Tno) and the course number (cno) in this table have a one-to-one relationship.

3. One-to-one relationship:

     For the relationship analyzed above, we can see the course number taught by the teacher by querying the teacher's job number, and we also need to add the teaching attribute to the Teacher persistent class. (This is considered from the teacher's point of view)

 ​​​​​​

 Then we look at their Mapper.xml configuration file, first see their corresponding interface:

 Next we write their Mapper.xml file

Then you can write test methods according to the interface.

 

 Code one:

1.TeacherMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.TeacherMapper">
    <select id="findTeacherByTno" parameterType="string" resultMap="classNameByID">
        select * from teacher where Tno=#{Tno}
    </select>
    <resultMap id="classNameByID" type="Teacher">
        <id property="Tno" column="Tno"></id>
        <result property="Tname" column="Tname"></result>
        <result property="Tsex" column="Tsex"></result>
        <result property="Tbirthday" column="Tbirthday"></result>
        <result property="deptno" column="deptno"></result>
        <association property="teaching" column="tno" javaType="Teaching"
                     select="org.example.mapper.TeachingMapper.findCnameByTno"/>
    </resultMap>
</mapper>

2.TeachingMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.TeachingMapper">
    <select id="findCnameByTno" parameterType="string"  resultType="Teaching">
        select * from teaching where tno=#{tno}
    </select>
</mapper>

Method two:

 Code two:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.TeacherMapper">
    <select id="findTeacherByTno" parameterType="string" resultMap="classNameByID">
        SELECT * FROM teacher a RIGHT JOIN teaching b on a.Tno=b.tno where a.Tno=#{Tno}
    </select>
<!--    <resultMap id="classNameByID" type="Teacher">-->
<!--        <id property="Tno" column="Tno"></id>-->
<!--        <result property="Tname" column="Tname"></result>-->
<!--        <result property="Tsex" column="Tsex"></result>-->
<!--        <result property="Tbirthday" column="Tbirthday"></result>-->
<!--        <result property="deptno" column="deptno"></result>-->
<!--        <association property="teaching" column="tno" javaType="Teaching"-->
<!--                     select="org.example.mapper.TeachingMapper.findCnameByTno"/>-->
<!--    </resultMap>-->
    <resultMap id="classNameByID" type="Teacher">
        <id property="Tno" column="Tno"></id>
        <result property="Tname" column="Tname"></result>
        <result property="Tsex" column="Tsex"></result>
        <result property="Tbirthday" column="Tbirthday"></result>
        <result property="deptno" column="deptno"></result>
        <association property="teaching" javaType="Teaching">
            <id property="cno" column="cno"></id>
            <result property="tno" column="tno"></result>
            <result property="cterm" column="cterm"></result>
        </association>
    </resultMap>
</mapper>

 3. One-to-many relationship:

       Use association to map to a ""complex type" attribute of JavaBean, such as JavaBean class, that is, a complex data type (JavaBean) attribute is nested inside JavaBean, which belongs to the association of complex type. However, it should be noted that association Elements only handle one-to-one associations.

      For example, a department may correspond to multiple teachers, then we need to query a department number and then return the name of the teacher belonging to this department number. At this time, we will use a one-to-many relationship, and then we will use collection to Achieved.

 

Add a List<Teacher> property that stores the Teacher collection in the Department persistent entity class

 Add method to TeacherMapper interface

List<Teacher> findTeacherBydeptno(String deptno);

 

TeacherMapper.xml 

   <select id="findTeacherBydeptno" parameterType="string" resultType="Teacher">
        SELECT * FROM teacher WHERE deptno=#{deptno}
    </select>

 test:

Code:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.DepartmentMapper">
<select id="findTeachersBydeptno" parameterType="string" resultMap="findteachsResult" >
    SELECT * FROM department WHERE deptno=#{deptno}
</select>
    <resultMap id="findteachsResult" type="Department">
        <id property="deptno" column="deptno"></id>
        <result property="deptname" column="deptname"></result>
        <result property="deptheader" column="deptheader"></result>
        <result property="office" column="office"></result>
        <collection property="teachers" column="deptno" ofType="Teacher"
        select="org.example.mapper.TeacherMapper.findTeacherBydeptno"/>
    </resultMap>
</mapper>

Method two:

 4. Many-to-many:

     In actual development, many-to-many relationships are also very common. In schools, a student chooses multiple courses, and many students choose a course. This is a many-to-many relationship. Below we understand how to implement a many-to-many relationship.

Then first create two persistent classes Sc and Student 

 

 and their corresponding interfaces:

package org.example.mapper;

import org.apache.ibatis.annotations.Param;
import org.example.po.Student;

import java.util.List;

public interface StudentMapper {
     List<Student> getStudent(@Param("cno")String cno);
}
package org.example.service;

import org.apache.ibatis.annotations.Param;
import org.example.po.Sc;

import java.util.List;

public interface ScService {
    List<Sc> getSc(String cno);
}

Mapper configuration file:

StudentMapper.xml:

 SCMapper.xml:

 Code:

ScMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.ScMapper">
    <resultMap id="Sclist1" type="Sc">
        <id property="sno" column="sno"></id>
        <result property="cno" column="cno"></result>
        <result property="degree" column="degree"></result>
        <collection property="students" ofType="Student" column="cno"
                    select="org.example.mapper.StudentMapper.getStudent"/>
    </resultMap>
    <select id="getSc" parameterType="string" resultMap="Sclist1">
        select * from sc
        <if test="cno!=null and cno!=''">where cno=#{cno}</if>
    </select>
</mapper>

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.example.mapper.StudentMapper">
<select id="getStudent" resultType="Student" parameterType="string">
    SELECT * from student WHERE sno IN (SELECT sno FROM sc WHERE cno=#{cno})
</select>
</mapper>

sevice part:

package org.example.service;

import org.apache.ibatis.annotations.Param;
import org.example.po.Sc;

import java.util.List;

public interface ScService {
    List<Sc> getSc(String cno);
}
package org.example.service;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.mapper.ScMapper;
import org.example.po.Sc;

import java.util.List;

public class ScServiceImpl implements ScService{
    private SqlSessionFactory sqlSessionFactory;
    public ScServiceImpl(SqlSessionFactory sqlSessionFactory){
        this.sqlSessionFactory=sqlSessionFactory;
    }
    @Override
    public List<Sc> getSc(String cno) {
        SqlSession sqlSession=sqlSessionFactory.openSession();
        ScMapper scMapper=sqlSession.getMapper(ScMapper.class);
        List<Sc> scs=scMapper.getSc(cno);
        sqlSession.close();
        return scs;
    }
}

testing method:

package org.example;

import static org.junit.Assert.assertTrue;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.mapper.TeacherMapper;
import org.example.po.Department;
import org.example.po.Sc;
import org.example.po.Student;
import org.example.po.Teacher;
import org.example.service.DepartmentServiceImpl;
import org.example.service.ScServiceImpl;
import org.example.service.TeacherServiceImpl;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Unit test for simple App.
 */
public class AppTest 
{
    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void init() throws IOException {
    InputStream in= Resources.getResourceAsStream("MyBatis_config.xml");
    this.sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
    }
//    @Test
//    public void findTeacherByTno(){
//        TeacherServiceImpl teacherService=new TeacherServiceImpl(sqlSessionFactory);
//        Teacher teacher=teacherService.findTeacherByTno("601");
//        System.out.println(teacher);
//    }
//    @Test
//    public void findteacherDeptno(){
//        DepartmentServiceImpl departmentService=new DepartmentServiceImpl(sqlSessionFactory);
//        List<Department> department=departmentService.findTeachersBydeptno("d01");
//
//    }
    @Test
    public void getstudent(){
        ScServiceImpl scService=new ScServiceImpl(sqlSessionFactory);
        List<Sc> scs=scService.getSc(null);
        for (Sc sc:scs){
            System.out.println("课程编号为"+sc.getCno()+"的课:");
            for(Student student:sc.getStudents()){
                System.out.println("学生姓名为:"+student.getSname()+"学生班级为:"+student.getClassno());
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_56233309/article/details/123584321