MyBatis is an excellent persistence layer framework that supports plain SQL queries, stored procedures and advanced mapping. MyBatis eliminates manual settings of almost all JDBC code and parameters and search encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and original mapping, mapping interfaces and Java's POJOs (Plain Old Java Objects) into records in the database.
In the previous article, I will introduce to you the tutorial on MyBatis one-to-one mapping.
Let me tell you about mybatis many-to-many mapping knowledge. The specific details are as follows:
There are many many-to-many examples, such as the relationship between the course and the students. A course can have multiple elective students, and a student can also take multiple subjects. The relationship between teachers and students: a teacher has multiple students, and a student has multiple teachers.
Take the relationship between students and the course as an example.
When we create data tables, we have two solutions:
The first type:
When creating a student data table, store a foreign key field for a course.
When creating a course data table, store a student's foreign key field.
But this has a big disadvantage, that is, if I want to delete the student table, there is a foreign key field of the course table.
Similarly, when I want to delete the course table, there are foreign key fields of the student table. Oh, it's not easy to deal with.
The second type:
We create student and course tables, and store their respective fields and records in the two tables.
Another common student_course table is used as an intermediate table to store foreign keys for student and course.
This is very convenient for us to delete the word table, so we adopt this solution.
Database Scripts
-- Many-to-many mapping -- Delete database drop database if exists mybatis;-- Create database create database if not exists mybatis default character set utf8;-- Select database use mybatis;-- Delete data table drop table if exists student;drop table if exists course;drop table if exists student_course;-- Create data table create table student(sid int(255),sname varchar(32),constraint pk_sid primary key (sid)); create table course(cid int(255),cname varchar(32),constraint pk_cid primary key (cid)); create table student_course(sid int(255),cid int(255),constraint pk_sid_cid primary key(sid,cid),constraint fk_sid foreign key (sid) references student(sid),constraint fk_cid foreign key (cid) references course(cid) );-- Test data insert into student (sid,sname) values (1,'ha');insert into student (sid,sname) values (2,'ha');insert into course (cid,cname) values (1,'java');insert into course (cid,cname) values (2,'.NET');insert into student_course (sid,cid) values (1,1);insert into student_course (sid,cid) values (1,2);insert into student_course (sid,cid) values (2,1);insert into student_course (sid,cid) values (2,2);
Create a new many2many.Course.java class
package many2many;import java.io.Serializable;import java.util.ArrayList;import java.util.List;/*** Course* @author Administrator**/@SuppressWarnings("serial")public class Course implements Serializable{private Integer cid;private String cname;private List<Student> students = new ArrayList<Student>();public Integer getCid() {return cid;}public void setCid(Integer cid) {this.cid = cid;}public String getCname() {return cname;}public void setCname(String cname) {this.cname = cname;}public List<Student> getStudents() {return students;}public void setStudents(List<Student> students) {this.students = students;}}Create a new many2many.Student.java class
package many2many;import java.io.Serializable;import java.util.ArrayList;import java.util.List;/*** Student class* @author Administrator**/@SuppressWarnings("serial")public class Student implements Serializable {private Integer sid;private String sname;private List<Course> courses = new ArrayList<Course>();public Integer getSid() {return sid;}public void setSid(Integer sid) {this.sid = sid;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public List<Course> getCourses() {return courses;}public void setCourses(List<Course> courses) {this.courses = courses;}}Create a new StudentMapper.xml file and CourseMapper.xml file
<?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="studentMapper"><resultMap type="many2many.Student" id="studentMap"><id property="sid" column="sid"/><result property="sname" column="sname"/><result property="sname"/></resultMap><?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="courseNamespace"><resultMap type="many2many.Course" id="courseMap"><id property="cid" column="cid"/><result property="cname" column="cname"/><resultMap><!-- Query the courses you took in "Haha" --><select id="findAllByName" parameterType="string" resultMap="courseMap">select c.cname,c.cid from student s,course c,student_course scwhere s.sid = sc.sid and c.cid = sc.cid and s.sname = #{sname};</select></mapper>Create a new persistence layer class StudentCourseDAO.java class
package many2many;import java.util.Iterator;import java.util.List;import one2many.Student;import org.apache.ibatis.session.SqlSession;import org.junit.Test;import util.MyBatisUtil;public class StudentCourseDAO {/*** Query "Haha" and took the elective courses* @param name Student's name* @return* @throws Exception*/public List<Course> findAllByName(String name) throws Exception{SqlSession sqlSession = null;try {sqlSession = MyBatisUtil.getSqlSession();return sqlSession.selectList("courseNamespace.findAllByName", name);} catch (Exception e) {e.printStackTrace();throw e;} finally{MyBatisUtil.closeSqlSession();}}@Testpublic void testFindAllByName() throws Exception{StudentCourseDAO dao = new StudentCourseDAO();List<Course> courses = dao.findAllByName("haha");for (Course course : courses) {System.out.println(course.getCid()+":"+course.getCname());}}}Load configuration file in mybatis.cfg.xml file
<!-- Load the mapping file--><mapper resource="one2one/CardMapper.xml"/><mapper resource="one2one/StudentMapper.xml"/><mapper resource="one2many/GradeMapper.xml"/><mapper resource="one2many/StudentMapper.xml"/><mapper resource="many2many/StudentMapper.xml"/><mapper resource="many2many/CourseMapper.xml"/><mapper resource="many2many/CourseMapper.xml"/><mapper resource="many2many/CourseMapper.xml"/><mapper resource="many2many/CourseMapper.xml"/><mappers>
The above is the first tutorial on MyBatis many-to-many mapping introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!