Mybatis学习笔记(二)

八、多表联合查询

(一) 多表联合查询概述

在开发过程中单表查询不能满足项目需求分析功能,对于复杂业务来讲,关联的表有几张,甚至几十张并且表与表之间的关系相当复杂。为了能够实业复杂功能业务,就必须进行多表查询,在mybatis中提供了多表查询的结果时映射标签,可以实现表之间的一对一、一对多、多对一、多对多关系映射。

(二) MyBatis实现一对一查询

1. 构建数据库表

        person(个人表) IdCard(身份证表)

CREATE TABLE person(
p_id INT NOT NULL AUTO_INCREMENT,
p_name VARCHAR(30),
PRIMARY KEY(p_id) 
);#IdCard表
CREATE TABLE idcard(
c_id INT NOT NULL AUTO_INCREMENT,
c_cardno VARCHAR(18),
c_uselife DATE,
c_person_id INT NOT NULL,
PRIMARY KEY(c_id),
FOREIGN KEY(c_person_id) REFERENCES person(p_id),
UNIQUE KEY(c_cardno));INSERT INTO person(p_name) VALUES('张三'),('李四');INSERT INTO idcard(c_cardno,c_uselife,c_person_id)
VALUES('110112199012127821','2029-10-10',1);
INSERT INTO idcard(c_cardno,c_uselife,c_person_id)
VALUES('120114199911103491','2030-12-01',2);

2.准备项目环境

3.嵌套结果方式查询

 3.1实体类创建

Person

package com.jn.entity;public class Person {private Integer id;private String name;public Person() {}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;}@Overridepublic String toString() {return "Person{" +"id=" + id +", name='" + name + '\'' +'}';}
}

IdCard 

package com.jn.entity;import java.util.Date;public class IdCard {private Integer id;private String cardno;private Date useLife;public IdCard() {}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getCardno() {return cardno;}public void setCardno(String cardno) {this.cardno = cardno;}public Date getUserLife() {return useLife;}public void setUserLife(Date userLife) {this.useLife = userLife;}@Overridepublic String toString() {return "IdCard{" +"id=" + id +", cardno='" + cardno + '\'' +", userLife=" + useLife +'}';}
}
3.2编写sql语句

实现查询个人信息时,也要查询个人所对应的身份证信息。

select p.*,c.* from
person p,
idcard c
where p.p_id=c.c_person_id and p.p_id=1;

3.3编写PersonIdCard类
package com.jn.entity;import java.util.Date;public class PersonIdCard extends Person{private String cardno;private Date useLife;public String getCardno() {return cardno;}public void setCardno(String cardno) {this.cardno = cardno;}public Date getUseLife() {return useLife;}public void setUseLife(Date useLife) {this.useLife = useLife;}
}
3.4定义持久层接口

PersonDao

package com.jn.dao;import com.jn.entity.PersonIdCard;public interface PersonDao {public PersonIdCard getPersonById(int id);
}
3.5定义 PersonDao.xml 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.PersonDao"><select id="getPersonById" resultMap="PersonResultMap">SELECT p.*,c.* from person p ,idcard c where p.p_id = c.c_person_id and p.p_id = 1;</select><resultMap id="PersonResultMap" type="PersonIdCard"><id column="p_id" property="id"></id><result column="p_id" property="id"></result><result column="p_name" property="name"></result><result column="c_cardno" property="cardno"></result><result column="c_uselife" property="useLife"></result></resultMap>
</mapper>
3.6创建 PersonTest 测试类
package com.jn.test;import com.jn.dao.PersonDao;
import com.jn.entity.PersonIdCard;
import com.jn.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;public class PersonTest {@Testpublic void testGetPersonById() throws Exception{//获取sqlSession对象SqlSession sqlSession = MyBatisUtils.getSession();//通过sqlSession获取PersonDao的代理对象PersonDao personDao = sqlSession.getMapper(PersonDao.class);PersonIdCard personIdCard = personDao.getPersonById(1);System.out.println(personIdCard);//commitsqlSession.close();MyBatisUtils.close(sqlSession);}
}
3.7测试结果

4.嵌套查询方式

前言

查的到底是什么?

        查的是一个对象Person,这个对象不仅包含了Person里面的属性,同时还包含了一个IdCard对象。然后把两个表里面的信息整合以便于后续处理。

4.1添加idCard属性

在person类里面添加idCard属性 

package com.jn.entity;public class Person {private Integer id;private String name;private IdCard idCard;public Person() {}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 IdCard getIdCard() {return idCard;}public void setIdCard(IdCard idCard) {this.idCard = idCard;}@Overridepublic String toString() {return "Person{" +"id=" + id +", name='" + name + '\'' +", idCard=" + idCard +'}';}
}
4.2持久层里面添加方法
package com.jn.dao;import com.jn.entity.Person;
import com.jn.entity.PersonIdCard;public interface PersonDao {public PersonIdCard getPersonById(Integer id);//嵌套查询的查询方法public Person getPersonById2(Integer id);
}
4.3持久层接口IdCardDao
package com.jn.dao;import com.jn.entity.Person;public interface IdCardDao {public Person getIdCardByPersonId(Integer id);
}
4.4定义 IdCardDao.xml 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.IdCardDao"><!--查询符合结果的IdCard对象并返回给命名空间IdCardDao下的getIdCardByPersonId函数,然后配合PersonDao.xml进行数据的联合查询
--><select id="getIdCardByPersonId"  parameterType="int" resultMap="IdCardResult">select * from idcard  where c_person_id  = #{id}</select><resultMap id="IdCardResult" type="IdCard"><id column="c_id" property="id"></id><result column="c_id" property="id"></result><result column="c_cardno" property="cardno"></result><result column="c_uselife" property="useLife"></result></resultMap>
</mapper>
4.5PersonDao.xml 配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.PersonDao"><!--嵌套结果的查询--><select id="getPersonById" resultMap="PersonResultMap">SELECT p.*,c.* from person p ,idcard c where p.p_id = c.c_person_id and p.p_id = 1;</select><resultMap id="PersonResultMap" type="PersonIdCard"><id column="p_id" property="id"></id><result column="p_id" property="id"></result><result column="p_name" property="name"></result><result column="c_cardno" property="cardno"></result><result column="c_uselife" property="useLife"></result></resultMap><!--嵌套查询的结果。根据id先查询到Person对象里面的字段信息,然后配合IdCard.xml查询返回的IdCard对象进行结合,然后返回一个getPersonById2函数的Person对象--><select id="getPersonById2" parameterType="int" resultMap="PersonResultMap2">select * from person where p_id = #{id}</select><resultMap id="PersonResultMap2" type="Person"><id column="p_id" property="id"></id><result column="p_name" property="name"></result><!--映射Person的复杂字段idCard对象属性--><association property="idCard" javaType="IdCard" column="p_id" select="com.jn.dao.IdCardDao.getIdCardByPersonId"></association></resultMap>
</mapper>

column:表示取上次查询出来的指定列的值,做为select属性所指定的查询的输入值。
select:表示指定的查询.

4.6加入测试方法
    //测试嵌套查询@Testpublic void testNestedQueryById() throws Exception{//获取sqlSession对象SqlSession sqlSession = MyBatisUtils.getSession();//通过sqlSession获取PersonDao的代理对象PersonDao personDao = sqlSession.getMapper(PersonDao.class);Person person = personDao.getPersonById2(1);System.out.println(person);MyBatisUtils.close(sqlSession);}
4.7测试结果

 到目前为止项目的结构目录

(三)MyBatis实现一对多查询

1.创建数据库表

department(部门表),employee(员工表)同时设定部门和员工表的关系

CREATE TABLE department(
d_id INT NOT NULL AUTO_INCREMENT,
d_name VARCHAR(100),
PRIMARY KEY(d_id)
);CREATE TABLE employee(
e_id INT NOT NULL AUTO_INCREMENT,
e_name VARCHAR(30),
e_gender VARCHAR(6),
e_age INT,
e_depart_id INT,
PRIMARY KEY(e_id),
FOREIGN KEY(e_depart_id) REFERENCES department(d_id)
);
-- 向 department 表中插入数据
INSERT INTO department (d_name) VALUES ('研发部');
INSERT INTO department (d_name) VALUES ('销售部');
INSERT INTO department (d_name) VALUES ('财务部');
INSERT INTO department (d_name) VALUES ('市场部');
INSERT INTO department (d_name) VALUES ('人力资源部');-- 向 employee 表中插入数据
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('张三', '男', 25, 1);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('李四', '女', 30, 1);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('王五', '男', 28, 2);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('赵六', '女', 32, 2);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('孙七', '男', 27, 3);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('周八', '男', 26, 1);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('吴九', '女', 29, 1);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('郑十', '男', 31, 2);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('钱十一', '女', 24, 3);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('刘十二', '男', 33, 4);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('陈十三', '女', 28, 4);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('杨十四', '男', 30, 5);
INSERT INTO employee (e_name, e_gender, e_age, e_depart_id) VALUES ('胡十五', '女', 27, 5);​

2.嵌套结果的方式

2.1实体类创建

Department类

package com.jn.entity;public class Department {private int id;private String 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;}
}

Employee类

package com.jn.entity;public class Employee {private int id;private String name;private String gender;private Integer age;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 String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Employee{" +"id=" + id +", name='" + name + '\'' +", gender='" + gender + '\'' +", age=" + age +'}';}
}
2.2编写sql查询语句
select d.*,e.* from department d,employee  e where d.d_id=e.e_depart_id and d.d_id=1;

2.3Department加入List

把Employee属性变为List集合作为Department的属性

package com.jn.entity;import java.util.List;public class Department {private int id;private String name;private List<Employee> emps;public Department() {}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 List<Employee> getEmps() {return emps;}public void setEmps(List<Employee> emps) {this.emps = emps;}@Overridepublic String toString() {return "Department{" +"id=" + id +", name='" + name + '\'' +", emps=" + emps +'}';}
}
2.4持久层DepartmentDao 
package com.jn.dao;import com.jn.entity.Department;public interface DepartmentDao {public Department getDepartById(Integer id);
}
2.5映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.DepartmentDao"><select id="getDepartById" parameterType="int" resultMap="getDepartmentMap">select d.*,e.* from department d,employee  e where d.d_id=e.e_depart_id and d.d_id=#{id}</select><resultMap id="getDepartmentMap" type="Department"><id column="d_id" property="id"></id><result column="d_name" property="name"></result><collection property="emps" ofType="Employee"><id column="e_id" property="id"></id><result column="e_name" property="name"></result><result column="e_gender" property="gender"></result><result column="e_age" property="age"></result></collection></resultMap>
</mapper>
2.6测试方法
package com.jn.test;import com.jn.dao.DepartmentDao;
import com.jn.entity.Department;
import com.jn.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;public class DepartmentTest {@Testpublic void testGetDepartmentById() throws Exception{//获取sqlSession对象SqlSession sqlSession = MyBatisUtils.getSession();//通过sqlSession对象得到DepartmentDao的接口代理对象DepartmentDao departmentDao = sqlSession.getMapper(DepartmentDao.class);Department department = departmentDao.getDepartById(1);System.out.println(department.getName());department.getEmps().forEach(System.out::println);//closesqlSession.close();}
}
2.7测试结果

 

3.嵌套查询的方式

3.1定义EmployeeDao
package com.jn.dao;import com.jn.entity.Employee;import java.util.List;public interface EmployeeDao {public List<Employee> getEmployeeById(Integer id);
}
3.2定义 EmployeeDao.xml 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.EmployeeDao"><!--配置employee的查询语句,返回一个Employee对象的集合--><select id="getEmployeeById" parameterType="int" resultMap="getEmployeeResultMap">select * from employee where e_depart_id = #{id}</select><resultMap id="getEmployeeResultMap" type="Employee"><id column="e_id" property="id"></id><result column="e_name" property="name"></result><result column="e_gender" property="gender"></result><result column="e_age" property="age"></result></resultMap>
</mapper>
3.3 DepartmentDao添加
package com.jn.dao;import com.jn.entity.Department;public interface DepartmentDao {public Department getDepartById(Integer id);public Department getDepartById2(Integer id);
}
3.4DepartmentDao.xml添加
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.DepartmentDao"><select id="getDepartById" parameterType="int" resultMap="getDepartmentMap">select d.*,e.* from department d,employee  e where d.d_id=e.e_depart_id and d.d_id=#{id}</select><resultMap id="getDepartmentMap" type="Department"><id column="d_id" property="id"></id><result column="d_name" property="name"></result><collection property="emps" ofType="Employee"><id column="e_id" property="id"></id><result column="e_name" property="name"></result><result column="e_gender" property="gender"></result><result column="e_age" property="age"></result></collection></resultMap><select id="getDepartById2" parameterType="int" resultMap="getDepartmentMap2">select * from department where d_id=#{id}</select><resultMap id="getDepartmentMap2" type="Department"><id column="d_id" property="id"></id><result column="d_name" property="name"></result><collection property="emps" ofType="Employee" column="d_id" select="com.jn.dao.EmployeeDao.getEmployeeById"></collection></resultMap>
</mapper>
3.5测试方法
    //嵌套查询@Testpublic void testGetDepartmentById2() throws Exception{//获取sqlSession对象SqlSession sqlSession = MyBatisUtils.getSession();//通过sqlSession对象得到DepartmentDao的接口代理对象DepartmentDao departmentDao = sqlSession.getMapper(DepartmentDao.class);Department department = departmentDao.getDepartById2(1);System.out.println(department.getName());department.getEmps().forEach(System.out::println);//closesqlSession.close();}
3.6测试结果

(三)MyBatis实现多对多查询

1.创建数据库表

CREATE TABLE student(sid INT NOT NULL AUTO_INCREMENT,sname VARCHAR(30),PRIMARY KEY (sid)
);CREATE TABLE teacher(tid INT NOT NULL AUTO_INCREMENT,tname VARCHAR(30),PRIMARY KEY (tid)
);CREATE TABLE student_teacher(s_id INT NOT NULL,t_id INT NOT NULL,PRIMARY KEY (s_id,t_id),FOREIGN KEY (s_id) REFERENCES student(sid),FOREIGN KEY (t_id) REFERENCES teacher(tid)
);
INSERT INTO student(sname) VALUES('张三'),('李四');
INSERT INTO teacher (tname) VALUES('刘老师'),('李老师');
INSERT INTO student(sname) VALUES('王五'),('赵六');
INSERT INTO teacher(tname) VALUES('张老师'),('王老师');
INSERT INTO student(sname) VALUES('孙七'),('周八');
INSERT INTO teacher(tname) VALUES('陈老师'),('杨老师');
INSERT INTO student(sname) VALUES('吴九'),('郑十');
INSERT INTO teacher(tname) VALUES('马老师'),('胡老师');
INSERT INTO student_teacher(s_id,t_id) VALUES(1,1),(1,2),(2,1),(3,3),(3,4),(4,3),(4,4),(5,5),(5,6),(6,5),(6,6),(7,7),(7,8),(8,7),(8,8);

2.嵌套结果方式

2.1创建数据模型

Student,Teacher,StudentTeacher

package com.jn.entity;public class Student {private int id;private int name;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getName() {return name;}public void setName(int name) {this.name = name;}
}
package com.jn.entity;public class Teacher {private int id;private String 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;}@Overridepublic String toString() {return "Teacher{" +"id=" + id +", name='" + name + '\'' +'}';}
}

package com.jn.entity;public class StudentTeacher {private int sid;private int tid;public int getSid() {return sid;}public void setSid(int sid) {this.sid = sid;}public int getTid() {return tid;}public void setTid(int tid) {this.tid = tid;}
}
2.2编写多对多的sql语句
select s.*,t.*,st.* from student s,teacher t,student_teacher st where s.sid = st.s_id and st.t_id=t.tid AND s.sid=1;

2.3S中加入List属性
package com.jn.entity;import java.util.List;public class Student {private int id;private String name;private List<StudentTeacher> studentTeacherList;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 List<StudentTeacher> getStudentTeacherList() {return studentTeacherList;}public void setStudentTeacherList(List<StudentTeacher> studentTeacherList) {this.studentTeacherList = studentTeacherList;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name=" + name +", studentTeacherList=" + studentTeacherList +'}';}
}
2.4ST加入Teacher属性
package com.jn.entity;public class StudentTeacher {private int sid;private int tid;private Teacher teacher;public int getSid() {return sid;}public void setSid(int sid) {this.sid = sid;}public int getTid() {return tid;}public void setTid(int tid) {this.tid = tid;}public Teacher getTeacher() {return teacher;}public void setTeacher(Teacher teacher) {this.teacher = teacher;}@Overridepublic String toString() {return "StudentTeacher{" +"sid=" + sid +", tid=" + tid +", teacher=" + teacher +'}';}
}
2.5tudentDao编写
package com.jn.dao;import com.jn.entity.Student;public interface StudentDao  {public Student getStudentById(Integer id);}
2.6SudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.StudentDao"><select id="getStudentById" parameterType="int" resultMap="getStudentMap">select s.*,t.*,st.* from student s,teacher t,student_teacher st where s.sid = st.s_id and st.t_id=t.tid AND s.sid=#{id}</select><resultMap id="getStudentMap" type="Student"><id column="sid" property="id"></id><result column="sname" property="name"></result><collection property="studentTeacherList" ofType="StudentTeacher"><result column="s_id" property="sid"></result><result column="t_id" property="tid"></result><association property="teacher" javaType="Teacher"><id column="tid" property="id"></id><result column="tname" property="name"></result></association></collection></resultMap>
</mapper>
2.7测试方法
package com.jn.test;import com.jn.dao.StudentDao;
import com.jn.entity.Student;
import com.jn.entity.StudentTeacher;
import com.jn.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;import java.util.List;public class StudentTest {@Testpublic void testGetStudentById()throws Exception{SqlSession sqlSession = MyBatisUtils.getSession();StudentDao studentDao = sqlSession.getMapper(StudentDao.class);Student student = studentDao.getStudentById(1);System.out.println(student.getName());List<StudentTeacher> studentTeacherList = student.getStudentTeacherList();studentTeacherList.forEach(System.out::println);}
}
2.8测试结果

3.嵌套查询方式

3.1TeacherDao
package com.jn.dao;import com.jn.entity.Teacher;public interface TeacherDao {public Teacher getTeacherById(Integer id);
}
 3.2TeacherDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.TeacherDao"><select id="getTeacherById" parameterType="int" resultType="Teacher">select tid id,tname name from teacher where tid =#{id}</select>
</mapper>
3.3StudentTeacherDao
package com.jn.dao;import com.jn.entity.StudentTeacher;import java.util.List;public interface StudentTeacherDao {public List<StudentTeacher> getStudentTeacherBySid(Integer id);
}
3.4StudentTeacherDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.StudentTeacherDao"><select id="getStudentTeacherBySid" parameterType="int" resultMap="getStudentTeacherMap">select * from student_teacher where s_id =#{id}</select><resultMap id="getStudentTeacherMap" type="StudentTeacher"><result column="s_id" property="sid"></result><result column="t_id" property="tid"></result><association property="teacher" column="t_id"  javaType="Teacher"select="com.jn.dao.TeacherDao.getTeacherById"></association></resultMap>
</mapper>
3.5StudentDao添加方法
package com.jn.dao;import com.jn.entity.Student;public interface StudentDao  {public Student getStudentById(Integer id);public Student getStudentById2(Integer id);}
3.6StudentDao.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jn.dao.StudentDao"><select id="getStudentById" parameterType="int" resultMap="getStudentMap">select s.*,t.*,st.* from student s,teacher t,student_teacher st where s.sid = st.s_id and st.t_id=t.tid AND s.sid=#{id}</select><resultMap id="getStudentMap" type="Student"><id column="sid" property="id"></id><result column="sname" property="name"></result><collection property="studentTeacherList" ofType="StudentTeacher"><result column="s_id" property="sid"></result><result column="t_id" property="tid"></result><association property="teacher" javaType="Teacher"><id column="tid" property="id"></id><result column="tname" property="name"></result></association></collection></resultMap><!--嵌套查询--><select id="getStudentById2" parameterType="int" resultMap="getStudentMap2">select * from student where sid=#{id}</select><resultMap id="getStudentMap2" type="Student"><id column="sid" property="id"></id><result column="sname" property="name"></result><collection property="studentTeacherList" ofType="StudentTeacher" column="sid"select="com.jn.dao.StudentTeacherDao.getStudentTeacherBySid"></collection></resultMap></mapper>
3.7测试方法
    //多对多的嵌套测试@Testpublic void testGetStudentById2()throws Exception{SqlSession sqlSession = MyBatisUtils.getSession();StudentDao studentDao = sqlSession.getMapper(StudentDao.class);Student student = studentDao.getStudentById2(1);System.out.println(student.getName());List<StudentTeacher> studentTeacherList = student.getStudentTeacherList();studentTeacherList.forEach(System.out::println);sqlSession.close();}
3.8测试结果

九、延迟加载策略

(一)简介

1.什么是延迟加载?

        延迟加载(lazy load)是(也称为懒加载)关联关系对象默认的加载方式,延迟加载机制是为了避免一些无谓的性能开销而提出来的,所谓延迟加载就是当在真正需要数据的时候,才真正执行数据加载操作。
        延迟加载,可以简单理解为,只有在使用的时候,才会发出sql语句进行查询。

2.为什么要使用延迟加载?

        减少访问数据库的频率,我们要访问的数据量过大时,明显用缓存不太合适,因为内存容量有限为了减少并发量,减少系统资源的消耗。

(二)局部延时加载

        注意:只有在嵌套查询的时候才能用到延时加载

        在mybatis中使用resultMap来实现一对一,一对多,多对多关系的操作。主要是通过 association、collection 实现一对一及一对多映射。association、collection 具备延迟加载功能。

 1.现象演示

在进行查询上述Employee与Department关联信息的时候,正常查询结果:

显示了两条sql语句的查询

然后把department.getEmps().forEach(System.out::println);给注释了查看结果

还是查询了两条sql语句

 2.局部解决

</resultMap>
相关联的查询标签上加 fetchType=”lazy”
fetchType默认值为eager 立即加载,Lazy为延时加载。

然后查看结果:

        发现只执行了一条sql语句

然后不进行注释查看结果 :

正常执行

(三)全局延时加载

        如果希望所有关联都需要延时加载,可以在mybatis的核心配置文件中进行配置,不用在collection或association中指定。默认全局开启。

1.配置setting

<settings>
<!--开启延时加载开关-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--关闭立即加载,实施按需加载-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>

2.测试 

测试正常 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/59280.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于 JAVASSM(Java + Spring + Spring MVC + MyBatis)框架开发一个九宫格日志系统

基于 JAVASSM&#xff08;Java Spring Spring MVC MyBatis&#xff09;框架开发一个九宫格日志系统 步骤一&#xff1a;需求分析 明确系统需要实现的功能&#xff0c;比如&#xff1a; 用户注册和登录添加日志&#xff08;包含标题、内容、图片&#xff09;查看日志列表…

rom定制系列------小米8青春版定制安卓14批量线刷固件 原生系统

&#x1f49d;&#x1f49d;&#x1f49d;小米8青春版。机型代码platina。官方最终版为 12.5.1安卓10的版本。客户需要安卓14的固件以便使用他们的软件。根据测试&#xff0c;原生pixeExpe固件适配兼容性较好。为方便客户批量进行刷写。修改固件为可fast批量刷写。整合底层分区…

浅谈UI自动化

⭐️前言⭐️ 本篇文章围绕UI自动化来展开&#xff0c;主要内容包括什么是UI自动化&#xff0c;常用的UI自动化框架&#xff0c;UI自动化原理等。 &#x1f349;欢迎点赞 &#x1f44d; 收藏 ⭐留言评论 &#x1f349;博主将持续更新学习记录收获&#xff0c;友友们有任何问题…

blender导入的图片渲染看不见,图片预览正常,但渲染不出

在使用Blender时&#xff0c;我们经常会遇到导入图片后在预览渲染中显示&#xff0c;但在实际渲染时图片消失的问题。本文将提供详细的解决方法&#xff0c;帮助大家解决“Blender导入的图片渲染图像不显示”的问题。 问题原因 导入的图片在Blender中只是一张图&#xff0c;并…

vue--vueCLI

何为CLI ■ CLI是Command-Line Interface,俗称脚手架. ■ 使用Vue.js开发大型应用时&#xff0c;我们需要考虑代码目录结构、项目结构和部署、热加载、代码单元测试等事情。&#xff08;vue 脚手架的作用&#xff09;&#xff0c; 而通过vue-cli即可&#xff1a;vue-cli 可以…

云专线优势有哪些?对接入网络有什么要求?

云专线是一种连接企业本地数据中心与云服务提供商之间的专用网络连接方式&#xff0c;具有以下优势&#xff1a; 高安全性&#xff1a;云专线提供了物理隔离的数据传输通道&#xff0c;减少了数据在公共互联网上传输时可能遭遇的安全风险。 低延迟&#xff1a;由于是直接连接&a…

Docker-- cgroups资源控制实战

上一篇&#xff1a;容器化和虚拟化 什么是cgroups&#xff1f; cgroups是Linux内核中的一项功能&#xff0c;最初由Google的工程师提出&#xff0c;后来被整合进Linux内核; 它允许用户将一系列系统任务及其子任务整合或分隔到按资源划分等级的不同组内&#xff0c;从而为系统…

算法: 链表题目练习

文章目录 链表题目练习两数相加两两交换链表中的节点重排链表合并 K 个升序链表K 个一组翻转链表 总结 链表题目练习 两数相加 坑: 两个链表都遍历完后,可能需要进位. class Solution {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode cur1 l1;ListNode…

js WebAPI黑马笔记(万字速通)

此笔记来自于黑马程序员&#xff0c;pink老师yyds 复习&#xff1a; splice() 方法用于添加或删除数组中的元素。 注意&#xff1a; 这种方法会改变原始数组。 删除数组&#xff1a; splice(起始位置&#xff0c; 删除的个数) 比如&#xff1a;1 let arr [red, green, b…

【Pikachu靶场:XSS系列】xss之过滤,xss之htmlspecialchars,xss之herf输出,xss之js输出通关啦

一、xss之过滤 <svg onloadalert("过关啦")> 二、xss之htmlspecialchars javascript:alert(123) 原理&#xff1a;输入测试文本为herf的属性值和内容值&#xff0c;所以转换思路直接变为js代码OK了 三、xss之href输出 JavaScript:alert(假客套) 原理&#x…

JS装备智能化储备管理体系优化改革

现代化的JS仓储管理方案&#xff0c;通过整合先进的RFID技术与三维模拟技术&#xff0c;为JS物流领域开创了新颖的改革浪潮。以下是对这两项尖端技术融合并用于战备物资管理的应用概述&#xff1a; 一、RFID技术在JS物资管理中的实践 RFID技术依靠无线电波实现无需直接接触的数…

缓存淘汰策略:Redis中的内存管理艺术

在现代应用架构中&#xff0c;缓存是提升性能的关键组件。 Redis&#xff0c;作为一个高性能的键值存储系统&#xff0c;因其快速的数据访问能力而被广泛使用。然而&#xff0c;由于物理内存的限制&#xff0c;Redis必须在存储空间和性能之间找到平衡&#xff0c;这就引出了缓…

AUTOSAR COM 与 LargeDataCOM 模块解析及 C++ 实现示例

AUTOSAR COM 和 LargeDataCOM 模块在功能和使用场景上有一些显著的区别。以下是它们的主要区别及具体的应用示例,最后用 C++ 源代码来解析说明。 AUTOSAR COM 模块 • 功能:主要用于处理标准大小的信号和 I-PDU(协议数据单元),提供了信号打包、解包、数据传输和接收等功能…

JavaWeb复习

在网络应用程序中有两种基本的结构&#xff0c;即C/S和B/S&#xff0c;对于c/s程序分为客户机和服务器两层&#xff0c;把应用软件按照在客户机端(通常由客户端维护困难)&#xff0c;通过网络与服务器进行相互通信。B/S结构却不用通知客户端安装某个软件&#xff0c;内容修改了…

qt获取本机IP和定位

前言&#xff1a; 在写一个天气预报模块时&#xff0c;需要一个定位功能&#xff0c;在网上翻来翻去才找着&#xff0c;放在这里留着回顾下&#xff0c;也帮下有需要的人 正文&#xff1a; 一开始我想着直接调用百度地图的API来定位&#xff0c; 然后我就想先获取本机IP的方…

python爬取旅游攻略(1)

参考网址&#xff1a; https://blog.csdn.net/m0_61981943/article/details/131262987 导入相关库&#xff0c;用get请求方式请求网页方式&#xff1a; import requests import parsel import csv import time import random url fhttps://travel.qunar.com/travelbook/list.…

Oracle OCP认证考试考点详解082系列12

题记&#xff1a; 本系列主要讲解Oracle OCP认证考试考点&#xff08;题目&#xff09;&#xff0c;适用于19C/21C,跟着学OCP考试必过。 56. 第56题&#xff1a; 题目 解析及答案&#xff1a; 关于企业管理器&#xff08;EM&#xff09;Express&#xff0c;以下哪两个陈述是…

Postgresql源码(137)执行器参数传递与使用

参考 《Postgresql源码&#xff08;127&#xff09;投影ExecProject的表达式执行分析》 0 总结速查 prepare p_04(int,int) as select b from tbl_01 where a $1 and b $2为例。 custom计划中&#xff0c;在表达式计算中使用参数的值&#xff0c;因为custom计划会带参数值&…

SPI通信详解-学习笔记

参考原文地址 SPI&#xff1a;高速、全双工&#xff0c;同步、通信总线 SPI主从模式 SPI分为主、从两种模式&#xff0c;一个SPI通讯系统需要包含一个&#xff08;且只能是一个&#xff09;主设备&#xff0c;一个或多个从设备。提供时钟的为主设备&#xff08;Master&#xff…

Day102漏洞发现-漏扫项目篇Poc开发Yaml语法插件一键生成匹配结果交互提取

知识点&#xff1a; 1、Nuclei-Poc开发-环境配置&编写流程 2、Nuclei-Poc开发-Yaml语法&匹配提取 3、Nuclei-Poc开发-BurpSuite一键生成插件 Nuclei-Poc开发-环境配置&编写流程 1、开发环境&#xff1a;VscodeYaml插件 Visual Studio Code - Code Editing. R…