Multiple students, corresponding to a teacher;
- For students, multiple students are related to one teacher
- For a teacher, there are many students in a teacher
Many to one
1. Create the corresponding sql (mybatis.student, mybatis.teacher); 2
2. Import the corresponding dependency (pom.xml)
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--Lombok https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
3. Teacher and Student classes (com.erdan.pojo)
import lombok.Data; @Data public class Student { private int id; private String name; //Multiple students can be the same teacher, that is, many to one private Teacher teacher; }
import lombok.Data; @Data public class Teacher { private int id; private String name; }
4. Corresponding StudentMapper and TeacherMapper (com.erdan.mapper)
import com.erdan.pojo.Student; import java.util.List; public interface StudentMapper { //Query all student information and corresponding teacher information //Get information about all students and their corresponding teachers public List<Student> getStudents(); }
public interface TeacherMapper { Teacher getTeacher(@Param("tid") int id); }
5. Corresponding tool class (com.erdan.utils)
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 java.io.IOException; import java.io.InputStream; public class MyBatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resources = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resources); // Factory mode sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } // Get the connection of sqlSession public static SqlSession getSqlSession(boolean b){ return sqlSessionFactory.openSession(); } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true); } }
6. Write mybatis-config.xml and db.properties in resources
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8 username=****** password=******
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="db.properties"/> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <typeAliases> <package name="com.erdan.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper class="com.erdan.dao.StudentMapper"/> <mapper class="com.erdan.dao.TeacherMapper"/> </mappers> </configuration>
7. Write the corresponding xml file (com.erdna.mapper) in resources
<?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="com.erdan.dao.StudentMapper"> <!-- Requirements: obtain information of all students and corresponding teachers Train of thought: 1. Access to all students' information 2. Get the teacher's information according to the teacher ID of the acquired student information 3. Think about the problem. In this way, the result set of students should include teachers. How to deal with it? We usually use association query in the database? 1. Make a result set mapping: StudentTeacher 2. The result set of studentteacher is Student 3. The attribute of teacher in students is teacher, and the corresponding database is tid. Multiple [1,...) students are associated with one teacher = > one to one, one to many 4. Check the official website to find: association - a complex type of association; use it to process association queries --> <select id="getStudents" resultMap="StudentTeacher"> select * from student </select> <resultMap id="StudentTeacher" type="Student"> <! -- association association property property property name javaType property type column column name in multi party table -- > <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <!-- The id passed here can write any value below when there is only one attribute Multi parameter configuration of column in association: column="{key=value,key=value}" In fact, it is in the form of key value pairs. Key is the value name passed to the next sql, and value is the field name of the sql query in segment 1. --> <select id="getTeacher" resultType="teacher"> select * from teacher where id = #{id} </select> </mapper>
<?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"> <!-- It turns out that we are all working on specific implementation sql --> <mapper namespace="com.erdan.dao.TeacherMapper"> </mapper>
8, test
@org.junit.Test public void testGetStudents(){ SqlSession session = MyBatisUtils.getSqlSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); List<Student> students = mapper.getStudents(); for (Student student : students){ System.out.println( "Student name:"+ student.getName() +"\t Teacher:"+student.getTeacher().getName()); } }
One to many
You can modify the part in one to many:
1. Student class and Teacher class:
import lombok.Data; @Data public class Student { private int id; private String name; private int tid; }
import lombok.Data; import java.util.List; @Data public class Teacher { private int id; private String name; //Obtain multiple students corresponding to one teacher private List<Student> students; }
2. TeacherMapper interface and StudentMapper interface:
import com.erdan.pojo.Teacher; public interface TeacherMapper { public Teacher getTeacher(int id); }
public interface StudentMapper { }
3. The corresponding xml file in resources:
<?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="com.erdan.mapper.StudentMapper"> </mapper>
<?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="com.erdan.mapper.TeacherMapper"> <!-- Train of thought: 1. Find out the student id, student name and teacher name from the student table and teacher table 2. Do result set mapping for the queried operations 1. For collection, use collection! Both JavaType and ofType are used to specify the object type JavaType is the type used to specify properties in pojo ofType specifies the type mapped to pojo in the list collection property. --> <select id="getTeacher" resultMap="TeacherStudent"> select s.id sid, s.name sname , t.name tname, t.id tid from student s,teacher t where s.tid = t.id and t.id=#{id} </select> <resultMap id="TeacherStudent" type="Teacher"> <result property="name" column="tname"/> <collection property="students" ofType="Student"> <result property="id" column="sid" /> <result property="name" column="sname" /> <result property="tid" column="tid" /> </collection> </resultMap> </mapper>
4. Test run:
import com.erdan.mapper.TeacherMapper; import com.erdan.pojo.Teacher; import com.erdan.utils.MyBatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test; public class MyTest { @Test public void toGetStudent(){ SqlSession session = MyBatisUtils.getSqlSession(); TeacherMapper mapper = session.getMapper(TeacherMapper.class); Teacher teacher = mapper.getTeacher(1); System.out.println(teacher.getName()); System.out.println(teacher.getStudents()); } }