MyBatis-----MyBatis---表级联系一对多

Posted Angelye

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis-----MyBatis---表级联系一对多相关的知识,希望对你有一定的参考价值。

一、核心配置文件

<?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>
     <!-- 最开始加载引用db.properties文件 -->
    <properties resource="db.properties"/>
    <!-- 取别名    以下情况别名为类名 -->
     <typeAliases>
         <package name="com.myBatis.entity"/>
     </typeAliases>
    <!-- 
        development : 开发模式
        work : 工作模式
     -->
    <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 resource="com/myBatis/mapper/classesMapper.xml"/>
        <mapper resource="com/myBatis/mapper/teacherMapper.xml"/>
        
    </mappers>
</configuration>

二、实体类

  Classes

package com.myBatis.entity;

import java.util.List;


public class Classes {
    private int id; // id===>c_id
    private String name; // name===>c_name
    /**
     * class表中有一个teacher_id字段,所以在Classes类中定义一个teacher属性,
     * 用于维护teacher和class之间的一对一关系,通过这个teacher属性就可以知道这个班级是由哪个老师负责的
     */
    private Teacher teacher;
    
    //使用一个List<Student>集合属性表示班级拥有的学生
     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 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 + "]";
    }
    
    //增删改要用到的两个构造方法
    public Classes(String name, Teacher teacher) {
        super();
        this.name = name;
        this.teacher = teacher;
    }
    public Classes() {
        super();
    }
    
    
}

  Teacher

package com.myBatis.entity;

public class Teacher {
    // 定义实体类的属性,与teacher表中的字段对应
    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 + "]";
    }
    public Teacher() {
        super();
    }
    public Teacher(int id) {
        super();
        this.id = id;
    }
    
    
}

  Student

package com.myBatis.entity;

public class Student {

    //定义属性,和student表中的字段对应
    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 + "]";
    }
}

三、映射文件

  classessMapper.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,namespace的值习惯上设置成包名+sql映射文件名,
    这样就能够保证namespace的值是唯一的 
    -->
    <mapper namespace="com.myBatis.mapper.classesMapper">
    <!-- 嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集
             封装联表查询的数据(去除重复的数据) 
             根据id查询得到一个user对象 -->
        <select id="getclassess" parameterType="int" resultMap="ClassResultMap">
             select * from classes c, teacher t where c.t_id=t.t_id and c.c_id=#{id}
        </select>
        <!-- 使用resultMap映射实体类和字段之间的一一对应关系 -->
        <resultMap type="Classes" id="ClassResultMap">
            <id property="id" column="c_id"/>
            <result property="name" column="c_name"/>
            <association property="teacher" javaType="Teacher">
                <id property="id" column="t_id"/>
                <result property="name" column="t_name"/>
            </association>
        </resultMap>
        <!--  根据id查询删除一个class 的t_id -->
        <delete id="deleteClasses" parameterType="Classes">
            delete from classes where c_id=#{id}
        </delete>
          <!-- 添加(Create) -->
        <insert id="addClasses" parameterType="Classes">
            insert into classes values(null,#{name},#{teacher.id})
        </insert>
         <!-- 修改班级所对应的老师(Update) -->
        <update id="updateClasses" parameterType="Classes">
            update classes set t_id=#{teacher.id} where c_id=#{id}
        </update>
        
     
     <!--一对多 -->   
        <!-- 
            根据classId查询对应的班级信息,包括学生,老师
         -->
    <!-- 
        嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集
        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="getClass3" parameterType="int" resultMap="ClassResultMap3">
        select * from classes c, teacher t,student s where c.t_id=t.t_id and c.c_id=s.class_id and  c.c_id=#{id}
    </select>
    <resultMap type="Classes" id="ClassResultMap3">
        <id property="id" column="c_id"/>
        <result property="name" column="c_name"/>
        <association property="teacher" column="t_id" javaType="Teacher">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </association>
        <!-- ofType指定students集合中的对象类型 -->
        <collection property="students" ofType="Student">
            <id property="id" column="s_id"/>
            <result property="name" column="s_name"/>
        </collection>
    </resultMap>
        
    </mapper>
    

  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,namespace的值习惯上设置成包名+sql映射文件名,
    这样就能够保证namespace的值是唯一的 
    -->
    <mapper namespace="com.myBatis.mapper.teacherMapper">
        <!-- 根据id查询得到一个user对象 -->
        <select id="getteacher" parameterType="int" resultMap="TeacherResultMap">
            select * from classes c, teacher t where c.t_id=t.t_id and t.t_id=#{id}
        </select>
        <!-- 使用resultMap映射实体类和字段之间的一一对应关系 -->
        <resultMap type="teacher" id="TeacherResultMap">
            <id property="id" column="t_id"/>
            <result property="name" column="t_name"/>
        </resultMap>
        
         <insert id="addTeacher" parameterType="Teacher">
            insert into teacher values(#{t_name})
        </insert>
        
    </mapper>
    

四、封装类

package com.myBatis.util;


import java.io.IOException;
import java.io.Reader;

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 myBtaisUtil {
    static Reader reader=null;
    static SqlSessionFactory sqlSessionFactory= null;
    static SqlSession sqlSession = null;
    /**
     * 加载核心配置文件
     * 获取SqlSessionFactory
     * @return SqlSessionFactory
     */
    public static SqlSessionFactory getsqlSessionFactory() {
        try {
            reader = Resources.getResourceAsReader("SqlMapConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }
    /**
     * 获取SqlSession
     * @return SqlSession
     */
    public static SqlSession getsqlSession() {
        return sqlSession= getsqlSessionFactory().openSession(true);
    }
}

五、测试类

package myBatisTest;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.myBatis.entity.Classes;
import com.myBatis.entity.Teacher;
import com.myBatis.util.myBtaisUtil;

public class TestUser {
    //查询
    @Test
    public void testGetClasses() {
        SqlSession sqlSession=myBtaisUtil.getsqlSession();
        String select = "com.myBatis.mapper.classesMapper.getClass3";
        Classes classes = sqlSession.selectOne(select, 1);
        System.out.println(classes);
    }
}

 

以上是关于MyBatis-----MyBatis---表级联系一对多的主要内容,如果未能解决你的问题,请参考以下文章

Athena - 改变表级联

Kettle的多表级联

多表级联统计

SQL Server:删除表级联等效?

SQL数据库怎么进行多表级联更新,求个存储过程

thinkphp在关联模型中三表级联查询