文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

在MyBatis中实现一对多查询和多对一查询的方式详解(各两种方式)

2024-04-02 19:55

关注

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一对多查询和多对一查询内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯