数据部分:
student表

set names utf8mb4; set foreign_key_checks = 0; -- ---------------------------- -- table structure for student -- ---------------------------- drop table if exists `student`; create table `student` ( `id` int(11) not null auto_increment, `sname` varchar(255) character set utf8 collate utf8_general_ci default null, `sex` varchar(255) character set utf8 collate utf8_general_ci default null, `age` int(11) default null, `t_id` int(11) default null, primary key (`id`) using btree ) engine = innodb auto_increment = 11 character set = utf8 collate = utf8_general_ci row_format = compact; -- ---------------------------- -- records of student -- ---------------------------- insert into `student` values (1, '张三', '男', 18, 1); insert into `student` values (2, '李四', '女', 18, 1); insert into `student` values (3, '王五', '男', 18, 1); insert into `student` values (4, '小白', '女', 18, 1); insert into `student` values (5, '小黑', '男', 18, 1); insert into `student` values (6, '小红', '女', 20, 2); insert into `student` values (7, '小李', '男', 20, 2); insert into `student` values (8, '小张', '女', 20, 2); insert into `student` values (9, '小赵', '男', 20, 2); insert into `student` values (10, '小王', '女', 20, 2); set foreign_key_checks = 1;
teacher表

set names utf8mb4; set foreign_key_checks = 0; -- ---------------------------- -- table structure for teacher -- ---------------------------- drop table if exists `teacher`; create table `teacher` ( `id` int(11) not null auto_increment, `tname` varchar(255) character set utf8 collate utf8_general_ci default null, primary key (`id`) using btree ) engine = innodb auto_increment = 3 character set = utf8 collate = utf8_general_ci row_format = compact; -- ---------------------------- -- records of teacher -- ---------------------------- insert into `teacher` values (1, '张老师'); insert into `teacher` values (2, '李老师'); set foreign_key_checks = 1;
查询老师的学生sql信息语句与查询结果如下:

查询学生的老师信息sql语句与查询结果如下:

直接查询
查询出来的数据用teacherstudents实体类进行封装
teacherstudents.java
package com.qcby.entity;
public class teacherstudents {
private integer id;
private string tname;
private string sname;
private string sex;
@override
public string tostring() {
return "teacherstudents{" +"id=" + id +", tname='" + tname + '\'' +", sname='" + sname + '\'' +", sex='" + sex + '\'' +'}';
}
public integer getid() {return id;}
public void setid(integer id) {this.id = id;}
public string gettname() {return tname;}
public void settname(string tname) {tname = tname;}
public string getsname() {return sname;}
public void setsname(string sname) {sname = sname;}
public string getsex() {return sex;}
public void setsex(string sex) {this.sex = sex;}
}
teacherstudentmapper.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="com.qcby.dao.teacherstudentsdao">
<select id="findteacherstudents" resulttype="com.qcby.entity.teacherstudents">
select teacher.*,student.sname,student.sex from teacher left join student on student.t_id = teacher.id
</select>
</mapper>
sqlmapconfig.xml
<mappers>
<mapper resource="mapper/teacherstudentsmapper.xml"></mapper>
</mappers>
teacherstudentsdao.java
package com.qcby.dao;
import com.qcby.entity.teacherstudents;
import java.util.list;
public interface teacherstudentsdao {
list<teacherstudents> findteacherstudents();
}
teacherstudentstest.java
import com.qcby.dao.teacherstudentsdao;
import com.qcby.entity.teacherstudents;
import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.sqlsession;
import org.apache.ibatis.session.sqlsessionfactory;
import org.apache.ibatis.session.sqlsessionfactorybuilder;
import org.junit.after;
import org.junit.before;
import org.junit.test;
import java.io.ioexception;
import java.io.inputstream;
import java.util.list;
public class teacherstudentstest {
private inputstream in = null;
private sqlsession session = null;
private teacherstudentsdao teacherstudentsdao = null;
@before //前置通知, 在方法执行之前执行
public void init() throws ioexception {
//加载主配置文件,目的是为了构建sqlsessionfactory对象
in = resources.getresourceasstream("sqlmapconfig.xml");
//创建sqlsessionfactory对象
sqlsessionfactory factory = new sqlsessionfactorybuilder().build(in);
//通过sqlsessionfactory工厂对象创建sqlsesssion对象
session = factory.opensession();
//通过session创建userdao接口代理对象
teacherstudentsdao = session.getmapper(teacherstudentsdao.class);
}
@after //@after: 后置通知, 在方法执行之后执行 。
public void destory() throws ioexception {
//释放资源
session.close();
in.close();
}
@test
public void findall(){
list<teacherstudents> list = teacherstudentsdao.findteacherstudents();
system.out.println(list.tostring());
}
}
直接查询的查询结果:

关联映射
student 表和 teacher 表存在着一对多与多对一的关系,我们介绍 mybatis 中处理关联关系的两种关联映射查询方式,分别是直接查询与分布查询。
直接查询通过 sql 的join(如left join、inner join)关联多个表,进行联合查询获取主表和关联表的所有所需字段,然后在<resultmap>中通过<association>一对一或<collection>一对多标签,定义主表与关联表字段到对应实体属性的映射规则,mybatis 会自动将查询结果分别封装为主实体和关联实体,并将关联实体注入主实体的关联属性中。
分步查询是分阶段完成查询,先执行主查询获取主实体数据及关联字段(select * from student),再由 mybatis 自动根据关联字段调用对应 mapper 方法,执行关联查询获取关联实体数据(select * from teacher where id = #{t_id}),最终将关联实体自动封装到主实体的关联属性中。可结合延迟加载,仅在使用关联数据时触发关联查询。
下面我们来看详细代码:
sqlmapconfig.xml
<mappers>
<mapper resource="mapper/studentmapper.xml"></mapper>
<mapper resource="mapper/teachermapper.xml"></mapper>
</mappers>
student.java
package com.qcby.entity;
public class student {
private integer id;
private string sname;
private string sex;
private integer age;
private integer t_id;
private teacher teacher;
@override
public string tostring() {
return "student{" +"id=" + id +", sname='" + sname + '\'' +", sex='" + sex + '\'' +", age=" + age +", t_id=" + t_id +", teacher=" + teacher +'}';
}
public teacher getteacher() {return teacher;}
public void setteacher(teacher teacher) {this.teacher = teacher;}
public integer getid() {return id;}
public void setid(integer id) {this.id = id;}
public string getsname() {return sname;}
public void setsname(string sname) {sname = sname;}
public string getsex() {return sex;}
public void setsex(string sex) {this.sex = sex;}
public integer getage() {return age;}
public void setage(integer age) {this.age = age;}
public integer gett_id() {return t_id;}
public void sett_id(integer t_id) {this.t_id = t_id;}
}
studentmapper.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="com.qcby.dao.studentdao">
<select id="findstudentteacher" resultmap="studentteacher">
select student.*,teacher.tname from student left join teacher on student.t_id = teacher.id
</select>
<resultmap id="studentteacher" type="com.qcby.entity.student">
<id property="id" column="id"/>
<result property="sname" column="sname"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<result property="t_id" column="t_id"/>
<association property="teacher" javatype="com.qcby.entity.teacher">
<result property="tname" column="tname"/>
</association>
</resultmap>
<select id="findstudentteacher1" resultmap="studentteacher1">
select * from student
</select>
<resultmap id="studentteacher1" type="com.qcby.entity.student">
<id property="id" column="id"/>
<result property="sname" column="sname"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<result property="t_id" column="t_id"/>
<association property="teacher" javatype="com.qcby.entity.teacher"
select="com.qcby.dao.teacherdao.findteacherbyt_id" column="t_id">
</association>
</resultmap>
<select id="findstudentbyt_id" resulttype="com.qcby.entity.student">
select * from student where t_id = #{id}
</select>
</mapper>
<select> 标签用于主查询,resultmap 属性用于指定映射规则<resultmap> 标签用于结果映射规则,其中 id 属性值要与 select 标签中的 resultmap 属性值相同,是映射规则的唯一标识,type 指定映射的目标实体类,result 映射普通字段,property=实体类中的属性名,column=数据库当中的字段,而 <association> 标签用于处理对象的关联信息,其中 property=关联对象的属性名、javatype=关联对象的类型、select=对应的查询方法、column=传递给关联查询的参数
studendao.java
package com.qcby.dao;
import com.qcby.entity.student;
import java.util.list;
public interface studentdao {
list<student> findstudentteacher();
list<student> findstudentteacher1();
student findstudentbyt_id(integer t_id);
}
studenttest.java
import com.qcby.dao.studentdao;
import com.qcby.entity.student;
import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.sqlsession;
import org.apache.ibatis.session.sqlsessionfactory;
import org.apache.ibatis.session.sqlsessionfactorybuilder;
import org.junit.after;
import org.junit.before;
import org.junit.test;
import java.io.ioexception;
import java.io.inputstream;
import java.util.list;
public class studenttest {
private inputstream in = null;
private sqlsession session = null;
private studentdao studentdao = null;
@before //前置通知, 在方法执行之前执行
public void init() throws ioexception {
//加载主配置文件,目的是为了构建sqlsessionfactory对象
in = resources.getresourceasstream("sqlmapconfig.xml");
//创建sqlsessionfactory对象
sqlsessionfactory factory = new sqlsessionfactorybuilder().build(in);
//通过sqlsessionfactory工厂对象创建sqlsesssion对象
session = factory.opensession();
//通过session创建userdao接口代理对象
studentdao = session.getmapper(studentdao.class);
}
@after //@after: 后置通知, 在方法执行之后执行 。
public void destory() throws ioexception {
//释放资源
session.close();
in.close();
}
@test
public void findstudentteacher(){
list<student> students = studentdao.findstudentteacher();
system.out.println(students.tostring());
}
@test
public void findstudentteacher1(){
list<student> students = studentdao.findstudentteacher();
system.out.println(students.tostring());
}
}
findstudentteacher() 直接查询结果如下:

findstudentteacher1() 分步查询结果如下:

teacher.java
package com.qcby.entity;
import java.util.list;
public class teacher {
private integer id;
private string tname;
private list<student> students;
@override
public string tostring() {
return "teacher{" +"id=" + id +", tname='" + tname + '\'' +", students=" + students +'}';
}
public list<student> getstudents() {return students;}
public void setstudents(list<student> students) {this.students = students;}
public integer getid() {return id;}
public void setid(integer id) {this.id = id;}
public string gettname() {return tname;}
public void settname(string tname) {tname = tname;}
}
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="com.qcby.dao.teacherdao">
<select id="getstudents" resultmap="teacherstudents">
select teacher.*,student.sname,student.sex from teacher left join student on student.t_id = teacher.id
</select>
<resultmap id="teacherstudents" type="com.qcby.entity.teacher">
<id property="id" column="id"/>
<result property="tname" column="tname"/>
<collection property="students" oftype="com.qcby.entity.student">
<result property="sname" column="sname"/>
<result property="sex" column="sex"/>
</collection>
</resultmap>
<select id="findteacherbyt_id" resulttype="com.qcby.entity.teacher">
select * from teacher where id = #{t_id}
</select>
<select id="getstudents1" resultmap="teacherstudents1">
select * from teacher
</select>
<resultmap id="teacherstudents1" type="com.qcby.entity.teacher">
<id property="id" column="id"/>
<result property="tname" column="tname"/>
<collection property="students" oftype="com.qcby.entity.student"
select="com.qcby.dao.studentdao.findstudentbyt_id" column="id" fetchtype="lazy"/>
</resultmap>
</mapper>
在 teacher.java 中 student 属性的类型是 list 集合,collection 标签用于处理集合映射到 student.java 中,oftype=集合泛型的类型
teacherdao.java
package com.qcby.dao;
import com.qcby.entity.teacher;
import java.util.list;
public interface teacherdao {
list<teacher> getstudents();
teacher findteacherbyt_id(integer t_id);
list<teacher> getstudents1();
}
teachertest.java
import com.qcby.dao.teacherdao;
import com.qcby.entity.teacher;
import com.qcby.entity.teacherstudents;
import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.sqlsession;
import org.apache.ibatis.session.sqlsessionfactory;
import org.apache.ibatis.session.sqlsessionfactorybuilder;
import org.junit.after;
import org.junit.before;
import org.junit.test;
import java.io.ioexception;
import java.io.inputstream;
import java.util.list;
public class teachertest {
private inputstream in = null;
private sqlsession session = null;
private teacherdao teacherdao = null;
@before //前置通知, 在方法执行之前执行
public void init() throws ioexception {
//加载主配置文件,目的是为了构建sqlsessionfactory对象
in = resources.getresourceasstream("sqlmapconfig.xml");
//创建sqlsessionfactory对象
sqlsessionfactory factory = new sqlsessionfactorybuilder().build(in);
//通过sqlsessionfactory工厂对象创建sqlsesssion对象
session = factory.opensession();
//通过session创建userdao接口代理对象
teacherdao = session.getmapper(teacherdao.class);
}
@after //@after: 后置通知, 在方法执行之后执行 。
public void destory() throws ioexception {
//释放资源
session.close();
in.close();
}
@test
public void getstudents(){
list<teacher> teachers = teacherdao.getstudents();
for (teacher teacher:teachers){
system.out.println(teacher);
}
}
@test
public void getstudents1(){
list<teacher> teachers = teacherdao.getstudents1();
for (teacher teacher:teachers){
system.out.println(teacher);
system.out.println(teacher.gettname());
system.out.println(teacher.getstudents());
}
}
}
getstudents() 直接查询结果如下:

getstudents1() 分步查询结果如下:

延迟加载
mybatis 的延迟加载(lazy loading)是一种优化数据库查询性能的机制,它允许在需要时才加载关联对象的数据,而不是在加载主对象时就立即加载所有关联数据。这种 “按需加载” 的方式可以减少不必要的数据库查询,提升系统性能。
延迟加载实现效果如图:

只执行了一个sql’语句,当查询该对象时,只加载该对象本身的属性,对于其关联的对象暂不加载,直到程序真正需要访问这些关联对象时,才会发起对应的数据库查询
如何配置延迟加载
- 全局配置:sqlmapconfig.xml
<setting name="lazyloadingenabled" value="true"/>
<setting name="aggressivelazyloading" value="false"/>
lazyloadingenabled 是延迟加载的全局开关,aggressivelazyloading 对 lazyloadingenabled 的补充配置,当开启延迟加载,aggressivelazyloading 再设置为 true 时,任何方式调用都会加载该对象的所有属性,设置为 false 则该属性将按需加载,若 lazyloadingenabled=false 关闭延迟加载时,此配置无效,所有关联对象都会立即加载。
- 局部配置:在映射文件中通过
<association>或<collection>标签中由 fetchtype 属性指定
<collection property="students" oftype="com.qcby.entity.student"
select="com.qcby.dao.studentdao.findstudentbyt_id" column="id" fetchtype="lazy"/>
fetchtype有两个值,一个是"lazy"为懒加载,一个是"eager"为立即加载
到此这篇关于mybatis关联映射的实现的文章就介绍到这了,更多相关mybatis关联映射内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论