首页 > 代码库 > MyBatis系列:(8)多对多映射

MyBatis系列:(8)多对多映射


0、准备SQL(mysql)

CREATE TABLE Teachers(
	tid INT(5) PRIMARY KEY,
	tname VARCHAR(10)
);

CREATE TABLE Courses(
	cid INT(5) PRIMARY KEY,
	cname VARCHAR(10)
);

CREATE TABLE R_Teacher_Course(
	tid INT(5),
	cid INT(5),
	PRIMARY KEY(tid,cid),
	CONSTRAINT r_teacher_fk FOREIGN KEY(tid) REFERENCES Teachers(tid),
	CONSTRAINT r_course_fk FOREIGN KEY(cid) REFERENCES Courses(cid)
);

INSERT INTO Teachers(tid,tname) VALUES(1,‘张老师‘);
INSERT INTO Teachers(tid,tname) VALUES(2,‘李老师‘);
INSERT INTO Teachers(tid,tname) VALUES(3,‘方老师‘);

INSERT INTO Courses(cid,cname) VALUES(1,‘语文‘);
INSERT INTO Courses(cid,cname) VALUES(2,‘数学‘);
INSERT INTO Courses(cid,cname) VALUES(3,‘英语‘);

INSERT INTO R_Teacher_Course(tid,cid) VALUES(1,1);
INSERT INTO R_Teacher_Course(tid,cid) VALUES(1,2);
INSERT INTO R_Teacher_Course(tid,cid) VALUES(2,2);
INSERT INTO R_Teacher_Course(tid,cid) VALUES(2,3);
INSERT INTO R_Teacher_Course(tid,cid) VALUES(3,3);
INSERT INTO R_Teacher_Course(tid,cid) VALUES(3,1);

SELECT * FROM Teachers;
SELECT * FROM Courses;
SELECT * FROM R_Teacher_Course;

SELECT t.tid,t.tname,c.cid,c.cname 
FROM teachers t 
	INNER JOIN r_teacher_course r ON t.tid=r.tid
	INNER JOIN courses c ON r.cid=c.cid


1、entity类

Teacher.java

package com.rk.entity;

import java.util.ArrayList;
import java.util.List;

public class Teacher {
    private Integer id;
    private String name;
    private List<Course> courses = new ArrayList<Course>();
    public Teacher(){}
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Course> getCourses() {
        return courses;
    }
    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }
    
}

Course.java

package com.rk.entity;

import java.util.ArrayList;
import java.util.List;

public class Course {
    private Integer id;
    private String name;
    private List<Teacher> teachers = new ArrayList<Teacher>();
    public Course(){}
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Teacher> getTeachers() {
        return teachers;
    }
    public void setTeachers(List<Teacher> teachers) {
        this.teachers = teachers;
    }
    
}


2、mybatis的映射文件

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="teacherNamespace">
    <resultMap type="com.rk.entity.Teacher" id="teacherMap">
        <id property="id" column="tid"/>
        <result property="name" column="tname"/>
    </resultMap>
    <select id="findTeacherByCourseName" parameterType="string" resultMap="teacherMap">
        select t.tid,t.tname,c.cid,c.cname 
        from teachers t 
                inner join r_teacher_course r on t.tid=r.tid
                inner join courses c on r.cid=c.cid
        where c.cname=#{courseName}
    </select>
</mapper>

CourseMapper.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="courseNamespace">
    <resultMap type="com.rk.entity.Course" id="courseMap">
        <id property="id" column="cid"/>
        <result property="name" column="cname"/>
    </resultMap>
    <select id="findCourseByTeacherName" parameterType="string" resultMap="courseMap">
        select c.cid,c.cname 
        from teachers t 
                inner join r_teacher_course r on t.tid=r.tid
                inner join courses c on r.cid=c.cid
        where t.tname=#{teacherName}       
    </select>
</mapper>


3、mybatis的主配置文件

mybatis.xml

<?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"></properties>
    <typeAliases>
        <typeAlias type="com.rk.entity.Emp" alias="emp"/>
    </typeAliases>
    <environments default="mysql_developement">
        <environment id="mysql_developement">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="http://www.mamicode.com/${mysql.driver}"/>
                <property name="url" value="http://www.mamicode.com/${mysql.url}"/>
                <property name="username" value="http://www.mamicode.com/${mysql.username}"/>
                <property name="password" value="http://www.mamicode.com/${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/rk/entity/TeacherMapper.xml"/>
        <mapper resource="com/rk/entity/CourseMapper.xml"/>
    </mappers>
</configuration>

db.properties

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/testdb
mysql.username=root
mysql.password=root


4、MyBatisUtils.java

package com.rk.utils;

import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    
    private MyBatisUtils(){}
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close();
            threadLocal.remove();
        }
    }
    
    public static void main(String[] args) {
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        Connection conn = sqlSession.getConnection();
        System.out.println(conn);
    }
}


5、TeacherCourseDao.java

package com.rk.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.rk.entity.Course;
import com.rk.entity.Teacher;
import com.rk.utils.MyBatisUtils;

public class TeacherCourseDao {
    public List<Teacher> findTeacherByCourseName(String courseName){
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.getSqlSession();
            List<Teacher> list = sqlSession.selectList("teacherNamespace.findTeacherByCourseName", courseName);
            sqlSession.commit();
            return list;
        }
        catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        finally{
            MyBatisUtils.closeSqlSession();
        }
    }
    
    public List<Course> findCourseByTeacherName(String teacherName){
        SqlSession sqlSession = null;
        try{
            sqlSession = MyBatisUtils.getSqlSession();
            List<Course> list = sqlSession.selectList("courseNamespace.findCourseByTeacherName", teacherName);
            sqlSession.commit();
            return list;
        }
        catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        finally{
            MyBatisUtils.closeSqlSession();
        }
    }
    
    public static void main(String[] args) {
        TeacherCourseDao dao = new TeacherCourseDao();
        List<Teacher> teacherList = dao.findTeacherByCourseName("数学");
        for(Teacher teacher : teacherList){
            System.out.println(teacher.getName());
        }
        
        List<Course> courseList = dao.findCourseByTeacherName("李老师");
        for(Course course : courseList){
            System.out.println(course.getName());
        }
    }
}



MyBatis系列:(8)多对多映射