MyBatis ----- 4. Implement the associated table query

The previous sections are single-table queries, but in practice it must often use multi-table associated with the query, this section describes the implementation of the associated table query

1. one association

1.1 to create a data table and add data

CREATE TABLE teacher(
    t_id INT PRIMARY KEY AUTO_INCREMENT, 
    t_name VARCHAR(20)
);
CREATE TABLE class(
    c_id INT PRIMARY KEY AUTO_INCREMENT, 
    c_name VARCHAR(20), 
    teacher_id INT
);
ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id);    

INSERT INTO teacher(t_name) VALUES('teacher1');
INSERT INTO teacher(t_name) VALUES('teacher2');

INSERT INTO class(c_name, teacher_id) VALUES('class_a', 1);
INSERT INTO class(c_name, teacher_id) VALUES('class_b', 2);

Create a table of teachers and class table, a class corresponding to a teacher, this is one association

1.2 class definition entities

public class Teacher {
    private int id;          
    private String name;    
    //get,set方法        
}
public class Classes {
    private int id;            
    private String name;
   private Teacher teacher; //teacher对象
//get,set方法 }

1.3 Definitions sql mapping file ClassMapper.xml

1: Direct linking table query
  using a subset of the results of the mapping to handle duplicate nested joint package with the results data table queries (deduplication data): nested results select * from class c, teacher t where c.teacher_id = t.t_id and c.c_id = 1
  <select id="getClass" parameterType="int" resultMap="Class">
      select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id}
  </select>
  <!-- 使用resultMap映射实体类和字段之间的一一对应关系 -->
  <resultMap type="com.zhiyou.zyl.bean.Classes" id="Class">
       <id property="id" column="c_id"/>
       <result property="name" column="c_name"/>
       <association property="teacher" javaType="com.zhiyou.zyl.bean.Teacher">
           <id property="id" column="t_id"/>
           <result property="name" column="t_name"/>
       </association>
   </resultMap>

  <Association> table is used to connect with the following attributes:  

  • property: name of the object properties
  • Type of object properties: javaType
  • column: foreign key column name corresponding to
  • select: Results using another query package
Second way: multiple queries: query as the result of another query conditions 
   the SELECT * = c_id the WHERE the FROM class. 1; // teacher_id. 1 = 
   the SELECT * the WHERE t_id = Teacher the FROM. 1; // use of the above-obtained teacher_id
   < SELECT ID = "getClass2" the parameterType = "int" resultMap = "Class2" > 
       SELECT * WHERE class from c_id ID = # {} 
    </ SELECT > 
      - <! One correspondence between the entity class and using the field map resultMap relations -> 
    < The resultMap type = "com.zhiyou.zyl.bean.Classes" ID = "Class2" > 
        < ID Property = "ID" column = "c_id" /> 
        < Result Property = "name" column = "c_name " /> 
        <association property="teacher" column="teacher_id" select="getTeacher"/>
    </resultMap>
    
    <select id="getTeacher" parameterType="int" resultType="com.zhiyou.zyl.bean.Teacher">
         SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
    </select>

1.4 registered in conf.xml file classMapper.xml

< Mappers > 
        <-! Register classMapper.xml file -> 
        < Mapper Resource = "COM / Zhiyou / Zyl / Mapper / classMapper.xml" /> 
</ mappers >

1.5 class definition of operator interface

package com.zhiyou.zyl.dao;
import com.zhiyou.zyl.bean.Classes;

public interface ClassesDao {
    /**
     * 查询
     * @return
     */
    public Classes getClass(int id);    
}

1.6 Test

class ClassesTest {
     static the SqlSession the session = null ;
     static ClassesDao CD;     
    @BeforeAll 
    static  void setUpBeforeClass () throws Exception { 
        String Resource = "conf.xml" ;
         // load mybatis profile (which also load the associated map file) 
        Reader Reader = Resources.getResourceAsReader (Resource);
         // build sqlSession factory 
        SqlSessionFactory sessionFactory = new new the SqlSessionFactoryBuilder () build (Reader);.
         // create a map file can be executed in the sql sqlSession 
        the session = sessionFactory.openSession();
        
        cd=session.getMapper(ClassesDao.class);
    }
    @AfterAll
    static void tearDownAfterClass() throws Exception {
        //提交
        session.commit();
    }
    @Test
    void testSelectById() {
        Classes classes=cd.getClass(1);
        System.out.println(classes.getStudent());
        System.out.println(classes);
    }

}

 

2. to-many association

2.1 I Am creating tables and insert data

CREATE TABLE student(
    s_id INT PRIMARY KEY AUTO_INCREMENT, 
    s_name VARCHAR(20), 
    class_id INT
);
INSERT INTO student(s_name, class_id) VALUES('student_A', 1);
INSERT INTO student(s_name, class_id) VALUES('student_B', 1);
INSERT INTO student(s_name, class_id) VALUES('student_C', 1);
INSERT INTO student(s_name, class_id) VALUES('student_D', 2);
INSERT INTO student(s_name, class_id) VALUES('student_E', 2);
INSERT INTO student(s_name, class_id) VALUES('student_F', 2);

Here a class has more students, which is associated with many

2.2 custom entity classes

  Creating student entity class

public class Student {
    private int sid;
    private String sname;
        //set,get方法
}

  Add List <Student> student attribute entity classes Classes

  

 

 2.3 modify the sql mapping file c lassMapper.xml

One way: Nested Results: By using nested result mapping to handle duplicate subset of the results combined 
SELECT * FROM class c, teacher t , student s WHERE c.teacher_id = t.t_id AND c.C_id = s.class_id AND c .c_id = 1
   <select id="getClass" parameterType="int" resultMap="Class">
         select * from class c, teacher t,student s where c.teacher_id=t.t_id and c.C_id=s.class_id and  c.c_id=#{id}
    </select>
    <resultMap type="com.zhiyou.zyl.bean.Classes" id="Class">
         <id property="id" column="c_id"/>
         <result property="name" column="c_name"/>
         <association property="teacher" column="teacher_id" javaType="com.zhiyou.zyl.bean.Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
         </association>
         <!-- ofType指定students集合中的对象类型 -->
        <collection property="students" ofType="com.zhiyou.zyl.bean.Student">
             <id property="id" column="s_id"/>
             <result property="name" column="s_name"/>
        </collection>    
 </resultMap>

  Collection using tags implements the mapping of the set of attributes

 

Second way: nested query: returns expected by executing another mapped SQL statement is complex type

    * The FROM class the WHERE c_id the SELECT =. 1; 
    teacher_id value SELECT * FROM teacher WHERE t_id = 1 // 1 is obtained on a query 
    SELECT * FROM student WHERE class_id = 1 // 1 is first obtained of the query field c_id value
 <select id="getClass2" parameterType="int" resultMap="Class2">
        select * from class where c_id=#{id}
      </select>
      <resultMap type="com.zhiyou.zyl.bean.Classes" id="Class2">
        <id property="id" column="c_id"/>
         <result property="name" column="c_name"/>
        <association property="teacher" column="teacher_id" javaType="com.zhiyou.zyl.bean.Teacher" select="getTeacher2"></association>
         <collection property="students" ofType="com.zhiyou.zyl.bean.Student" column="c_id" select="getStudent"></collection>
      </resultMap>
      
      <select id="getTeacher2" parameterType="int" resultType="com.zhiyou.zyl.bean.Teacher">
         SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
      </select>
      
      <select id="getStudent" parameterType="int" resultType="com.zhiyou.zyl.bean.Student">
        SELECT s_id id, s_name name FROM student WHERE class_id=#{id}
      </select>

2.4 Test Results

Classes [cid=1, cname=bj_a, tid=1, teacher=Teacher [tid=1, tname=LS1], 
student=[Student [sid=1, sname=xs_A], Student [sid=2, sname=xs_B], Student [sid=3, sname=xs_C]]]


Guess you like

Origin www.cnblogs.com/zyl187110/p/11442683.html