1. One-to-one association
1.1. Propose requirements
Query class information based on class id (information with teacher)
1.2. Create tables and data
Create a teacher table and a class table. Here we assume that a teacher is only responsible for teaching one class, so the relationship between the teacher and the class is a one-to-one relationship.
CREATE TABLE teacher( t_id INT PRIMARY KEY AUTO_INCREMENT, t_name VARCHAR() ); CREATE TABLE class( c_id INT PRIMARY KEY AUTO_INCREMENT, c_name VARCHAR(), 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('teacher'); INSERT INTO teacher(t_name) VALUES('teacher'); INSERT INTO class(c_name, teacher_id) VALUES('class_a', ); INSERT INTO class(c_name, teacher_id) VALUES('class_b', 2); The relationship between tables is as follows:
1.3. Define entity classes
1. Teacher class, Teacher class is the entity class corresponding to the teacher table.
package me.gacl.domain; /** * @author gacl * Define the entity class corresponding to the teacher table*/ public class Teacher { //Define the attributes of the entity class, corresponding to the fields in the teacher table private int id; //id===>t_id private String name; //name===>t_name public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Teacher [id=" + id + ", name=" + name + "]"; } }2. Classes class, Classes class is the entity class corresponding to the class table
package me.gacl.domain; /** * @author gacl * Define the entity class corresponding to the class table*/ public class Classes { //Define the attributes of the entity class, corresponding to the fields in the class table private int id; //id===>c_id private String name; //name===>c_name /** * There is a teacher_id field in the class table, so a teacher attribute is defined in the Classes class, * is used to maintain the one-to-one relationship between teacher and class. Through this teacher attribute, you can know which teacher is responsible for this class*/ private Teacher teacher; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } @Override public String toString() { return "Classes [id=" + id + ", name=" + name + ", teacher=" + teacher+ "]"; } } 1.4. Define the sql mapping file classMapper.xml
<?xml version="." encoding="UTF-" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper .//EN" "http://mybatis.org/dtd/mybatis--mapper.dtd"> <!-- Specify a unique namespace for this mapper. The value of the namespace is conventionally set to the package name + sql mapping file name, so that the value of the namespace can be guaranteed to be unique. For example, namespace="me.gacl.mapping.classMapper" is me.gacl.mapping (package name) + classMapper (classMapper.xml file removal suffix) --> <mapper namespace="me.gacl.mapping.classMapper"> <!-- Query class information based on class id (with teacher's information) ##. Joint table query SELECT * FROM class c,teacher t WHERE c.teacher_id=t.t_id AND c.c_id=; ##. Execute two queries SELECT * FROM class WHERE c_id=; //teacher_id= SELECT * FROM teacher WHERE t_id=;//Use the teacher_id obtained above --> <!-- Method 1: Nested results: Use nested result map to process the subset of duplicate joint results to encapsulate the data of the joint table query (remove duplicate data) select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id= --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id} </select> <!-- Use resultMap to map a one-to-one correspondence between entity classes and fields --> <resultMap type="me.gacl.domain.Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="me.gacl.domain.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap> <!-- Method 2: Nested query: Return the expected complex type by executing another SQL mapping statement SELECT * FROM class WHERE c_id=; SELECT * FROM teacher WHERE t_id= // is the value of teacher_id obtained from the previous query --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class where c_id=#{id} </select> <!-- Use resultMap to map a one-to-one correspondence between entity class and field--> <resultMap type="me.gacl.domain.Classes" id="ClassResultMap"> <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="me.gacl.domain.Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select> </mapper> Register classMapper.xml in conf.xml file
<mappers> <!-- Register the classMapper.xml file. classMapper.xml is located in the package me.gacl.mapping, so the resource is written as me/gacl/mapping/classMapper.xml--> <mapper resource="me/gacl/mapping/classMapper.xml"/></mappers>
1.5. Write unit test code
package me.gacl.test; import me.gacl.domain.Classes; import me.gacl.util.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class Test { @Test public void testGetClass(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); /** * Map SQL Identification String, * me.gacl.mapping.classMapper is the value of the namespace attribute of the mapper tag in the classMapper.xml file, * getClass is the id attribute value of the select tag. The SQL to be executed can be found through the id attribute value of the select tag */ String statement = "me.gacl.mapping.classMapper.getClass";//Mapping the sql's identification string//Execute the query operation and automatically encapsulate the query result into a Classes object and return Classes clazz = sqlSession.selectOne(statement,);//Query the record with id in the class table//After executing SQL using SqlSession sqlSession.close(); System.out.println(clazz);//Print result: Classes [id=, name=class_a, teacher=Teacher [id=, name=teacher]] } @Test public void testGetClass(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); /** * Map SQL Identification String, * me.gacl.mapping.classMapper is the value of the namespace attribute of the mapper tag in the classMapper.xml file, * getClass is the id attribute value of the select tag. The SQL to be executed can be found through the id attribute value of the select tag */ String statement = "me.gacl.mapping.classMapper.getClass";//Mapping the sql's identification string//Execute query operations and automatically encapsulate the query results into Classes object Return Classes clazz = sqlSession.selectOne(statement,);//Query the record with id in the class table//After using SqlSession to execute SQL, you need to close SqlSession sqlSession.close(); System.out.println(clazz);//Print result: Classes [id=, name=class_a, teacher=Teacher [id=, name=teacher]] } } 1.6. Summary of MyBatis one-to-one association query
MyBatis uses the association tag to solve one-to-one association queries. The properties available to the association tag are as follows:
•property: The name of the object property
•javaType: The type of object attribute
•column: The corresponding foreign key field name
•select: Use another query to encapsulate the result
2. One-to-many association
2.1. Propose requirements
Query the corresponding class information according to classId, including students and teachers
2.2. Create tables and data
In the one-to-one correlation query demonstration above, we have created the class table and the teacher table, so here we create another student table
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); 2.3. Define entity classes
1. Student class
package me.gacl.domain; /** * @author gacl * Define the entity class corresponding to the student table*/ public class Student { //Define the attributes, corresponding to the fields in the student table private int id; //id===>s_id private String name; //name===>s_name public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + "]"; } } 2. Modify the Classes class, add a List<Student> students attribute, and use a List<Student> collection attribute to represent the students owned by the class, as follows:
package me.gacl.domain; import java.util.List; /** * @author gacl * Define the entity class corresponding to the class table*/ public class Classes { //Define the attributes of the entity class, corresponding to the fields in the class table private int id; //id===>c_id private String name; //name===>c_name /** * There is a teacher_id field in the class table, so a teacher attribute is defined in the Classes class, * is used to maintain the one-to-one relationship between teacher and class. Through this teacher attribute, you can know which teacher is responsible for this class*/ private Teacher teacher; //Use a List<Student> collection attribute to represent students owned by the class private List<Student> students; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } @Override public String toString() { return "Classes [id=" + id + ", name=" + name + ", teacher=" + teacher + ", students=" + students + "]"; } } 2.4. Modify the sql mapping file classMapper.xml
Add the following SQL mapping information
<!-- Query the corresponding class information according to classId, including students and teachers --> <!-- Method 1: Nested results: Use nested result map to process a subset of repeated joint results 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= --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> 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="me.gacl.domain.Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> <!-- ofType Specifies the object type in the students collection--> <collection property="students" ofType="me.gacl.domain.Student"> <id property="id" column="s_id"/> <result property="name" column="s_name"/> </collection> </resultMap> <!-- Method 2: Nested query: Return the expected complex type by executing another SQL mapping statement SELECT * FROM class WHERE c_id=; SELECT * FROM teacher WHERE t_id= // is the value of teacher_id obtained by the previous query SELECT * FROM student WHERE class_id= //is the value of the c_id field obtained by the first query --> <select id="getClass" parameterType="int" resultMap="ClassResultMap"> select * from class where c_id=#{id} </select> <resultMap type="me.gacl.domain.Classes" id="ClassResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" column="teacher_id" javaType="me.gacl.domain.Teacher" select="getTeacher"></association> <collection property="students" ofType="me.gacl.domain.Student" column="c_id" select="getStudent"></collection> </resultMap> <select id="getTeacher" parameterType="int" resultType="me.gacl.domain.Teacher"> SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id} </select> <select id="getStudent" parameterType="int" resultType="me.gacl.domain.Student"> SELECT s_id id, s_name name FROM student WHERE class_id=#{id} </select> 2.5. Write unit test code
package me.gacl.test; import me.gacl.domain.Classes; import me.gacl.util.MyBatisUtil; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class Test { @Test public void testGetClass(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); /** * Map SQL Identification String, * me.gacl.mapping.classMapper is the value of the namespace attribute of the mapper tag in the classMapper.xml file, * getClass is the id attribute value of the select tag. The SQL to be executed can be found through the id attribute value of the select tag */ String statement = "me.gacl.mapping.classMapper.getClass";//Mapping the sql's identification string//Execute the query operation and automatically encapsulate the query result into a Classes object and return Classes clazz = sqlSession.selectOne(statement,);//Query the record with id in the class table//After executing SQL using SqlSession sqlSession.close(); //Print the result: Classes [id=, name=class_a, teacher=Teacher [id=, name=teacher], students=[Student [id=, name=student_A], Student [id=, name=student_B], Student [id=, name=student_C]]] System.out.println(clazz); } @Test public void testGetClass(){ SqlSession sqlSession = MyBatisUtil.getSqlSession(); /** * Map SQL Identification String, * me.gacl.mapping.classMapper is the value of the namespace attribute of the mapper tag in the classMapper.xml file, * getClass is the id attribute value of the select tag. The SQL to be executed can be found through the id attribute value of the select tag */ String statement = "me.gacl.mapping.classMapper.getClass";//Mapping the sql's identification string//Execute the query operation and automatically encapsulate the query result into a Classes object and return Classes clazz = sqlSession.selectOne(statement,);//Query the record with id in the class table//After executing SQL using SqlSession sqlSession.close(); //Print the result: Classes [id=, name=class_a, teacher=Teacher [id=, name=teacher], students=[Student [id=, name=student_A], Student [id=, name=student_B], Student [id=, name=student_C]]] System.out.println(clazz); } } 2.6. Summary of MyBatis one-to-many association query
MyBatis uses the collection tag to solve one-to-many association queries, and the ofType attribute specifies the object type of elements in the collection.
About MyBatis Learning Tutorial (V) - I will introduce so much to you about implementing association table query, I hope it will be helpful to you!