在MyBatis中實現一對多查詢和多對一查詢的方式詳解(各兩種方式)

1、多對一

1、1環境搭建

數據庫

CREATE TABLE teacher (
id INT(10) NOT NULL,
NAME VARCHAR(64) DEFAULT NULL,

PRIMARY KEY (id),
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO teacher (id ,NAME) VALUES (1,'羅老師');

CREATE TABLE student (
id INT(10) NOT NULL,
NAME VARCHAR(64) DEFAULT NULL,
tid INT(10) DEFAULT NULL,
PRIMARY KEY (id),
KEY fktid (tid),
CONSTRAINT fktid FOREIGN KEY (tid) REFERENCES teacher (id)
)
ALTER TABLE student ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO student (id ,NAME ,tid) VALUES (1,'小明',1);
INSERT INTO student (id ,NAME ,tid) VALUES (2,'小紅',1);
INSERT INTO student (id ,NAME ,tid) VALUES (3,'小張',1);
INSERT INTO student (id ,NAME ,tid) VALUES (5,'小羅',1);

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>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/><!--日記log4j-->
    </settings>
    <typeAliases>
        <package name="com.Google.pojo"/><!--給實體類取別名-->
    </typeAliases>
    <!--<typeAliases>
        <typeAlias type="com.Google.pojo.User" alias="user"/>
    </typeAliases>-->
    <environments default="development"><!--可以創建多個環境-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/><!--加載驅動-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/><!--連接數據庫-->
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--註冊接口-->
    <mappers>
        <mapper resource="com/Google/Dao/StudentMapper.xml"/>
        <mapper resource="com/Google/Dao/TeacherMapper.xml"/>
    </mappers>
</configuration>

1、2編寫實體類、

學生·

@Data
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

老師·

@Data
public class Teacher {
    private int id;
    private String name;
}

1、3編寫接口方法

public interface  StudentMapper {
    List<Student> getStudentList();
    List<Student> getStudentList1();
}

1、4編寫Mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Google.Dao.StudentMapper">
    <!--按照查詢嵌套處理-->
    <select id="getStudentList" resultMap="StudentMap">
        select * from student
    </select>
    <resultMap id="StudentMap" type="Student" >
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher
    </select>
    <!--按照結果嵌套處理-->
    <select id="getStudentList1" resultMap="StudentMap1">
        select s.id sid,s.name sname,t.name tname
        from Student s,Teacher t
        where s.tid=t.id
    </select>
    <resultMap id="StudentMap1" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher" >
            <result property="name" column="tname"/>
        </association>
    </resultMap>
</mapper>

1、5實現

package com.Google.Dao;

import com.Google.pojo.Student;
import com.Google.units.sqlSessionFactory;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class StudentMapperText {
    @Test
    public void getStudent(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudentList();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }
    @Test
    public void getStudent1(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> studentList = mapper.getStudentList1();
        for (Student student : studentList) {
            System.out.println(student);
        }
        sqlSession.close();
    }
}

1、6運行結果

Student(id=1, name=小明, teacher=Teacher(id=0, name=羅老師))
Student(id=2, name=小紅, teacher=Teacher(id=0, name=羅老師))
Student(id=3, name=小張, teacher=Teacher(id=0, name=羅老師))
Student(id=4, name=小王, teacher=Teacher(id=0, name=羅老師))
Student(id=5, name=小羅, teacher=Teacher(id=0, name=羅老師))

2、一對多

2、1環境搭建和一對多一樣

2、2編寫實體類

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
@Data
public class Teacher {
    private int id;
    private String name;
    //一個老師擁有多個學生,給老師創建一個學生集合
    private List<Student> student;
}

2、3編寫接口的方法

public interface TeacherMapper {
    Teacher getTeacher(@Param("tid") int id);

    Teacher getTeacher1(@Param("tid") int id);
}

2、4編寫Mapper配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Google.Dao.TeacherMapper">

    <!--按結果嵌套查詢-->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.id tid, t.name tname
        from student s,
             teacher t
        where s.tid = t.id
          and t.id = #{tid}
    </select>
    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--ofType="" 用於獲取集合中泛型的信息-->
        <collection property="student" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
    <!--嵌套表查詢(子查詢)-->
    <select id="getTeacher1" resultMap="TeacherStudent1">
        select * from teacher where id=#{tid}
    </select>
    <resultMap id="TeacherStudent1" type="Teacher">
        <result property="id" column="id"/>
        <collection property="student" javaType="ArrayList" ofType="Student" select="getStudetByID" column="id"/>
    </resultMap>
    <select id="getStudetByID" resultType="Student">
        select * from student where tid=#{tid}
    </select>
</mapper>

2、5實現

public class TeacherMapperText {
    @Test
    public void getTeacher(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }
    @Test
    public void getTeacher1(){
        SqlSession sqlSession = sqlSessionFactory.getsqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = mapper.getTeacher1(1);
        System.out.println(teacher1);
        sqlSession.close();
    }
}

2、6運行結果

Teacher(id=1, name=羅老師, student=[Student(id=1, name=小明, tid=1), Student(id=2, name=小紅, tid=1), Student(id=3, name=小張, tid=1), Student(id=4, name=小王, tid=1), Student(id=5, name=小羅, tid=1)])

到此這篇關於在MyBatis中實現一對多查詢,和多對一查詢(各兩種方式)的文章就介紹到這瞭,更多相關MyBatis一對多查詢和多對一查詢內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: