在项目开发中,我们有遇到的对象关系通常是复杂的,每个对象并不是单独的。比如学生和老师之间关系,一个老师有多个学生,每个学生会对应一个老师(这里的老师主要是班主任),这种关系其实就是一对多的关系。Mybatis在处理这种关系的时候,也是有自己的办法的。接下来就讲述一下在Mybatis中处理一对多关系的映射。
1、先捋清楚学生和老师的ER模型以及数据库表
数据库表中主要是在学生端的表中有一个外键引用老师的id,所以两张表结构如下:
-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`course` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
`sex` tinyint(1) DEFAULT NULL,
`teacherId` bigint(20) DEFAULT NULL, --这个字段表示学生对应的老师
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
2、创建对应的实体java对象
//Teacher.java,老师是一方
public class Teacher {
private Long id;//主键
private String name;
private String course;
private List<Student> students;//老师端定义一个学生列表集合
//setter,getter
}
//Student.java,学生是多方
public class Student {
private Long id;
private String name;
private Boolean sex;
private Long teacherId;// 学生对应的老师的id
private Teacher teacher;//学生端定义一个所属老师的对象
//setter,getter
}
3、为每个对象配置映射文件
Teacher.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.gusi.demo.idao.ITeacher">
<!--该结果集映射只映射老师的基本属性,没有映射老师所对应的学生集合 -->
<resultMap type="TeacherAlias" id="TeacherResult">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="course" jdbcType="VARCHAR" property="course" />
</resultMap>
<!--该结果集映射了老师的基本信息以及老师所有学生的信息 -->
<resultMap type="TeacherAlias" id="TeacherWithShtudentResult">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="course" jdbcType="VARCHAR" property="course" />
<!--一对多关系的时候,一方使用collection标签映射多方,属性就是Teacher对象中的集合属性名称。因为是集合类型,所以不能再直接使用column属性,需要使用另一个映射对象结果集合,该结果集合也是通过namespace.id指定。当然也可以不引用其他结果集合,在标签内部可以自己在定义临时的resultMap标签对象,比如id,result标签 -->
<collection property="students"
resultMap="com.gusi.demo.idao.IStudent.StudentResult"></collection>
</resultMap>
<!--查询老师,但是不涉及到老师的所有学生 -->
<select id="queryOneTeacher" parameterType="long" resultMap="TeacherResult">
SELECT a.id,a.name,a.course
FROM teacher a
WHERE a.id = #{id:BIGINT}
</select>
<!--这里查询结果中就包含老师所有的学生集合,使用到了多表连接查询 -->
<select id="queryOneTeacherWithStudent" parameterType="long" resultMap="TeacherWithShtudentResult">
<!-- 对于相同的属性名称s.id和t.id以及s.name和t.name,一定要注意起别名,不然会冲突 -->
SELECT a.id,a.name,a.course,b.id sid,b.name
sname,b.sex,b.teacherId
FROM teacher a left join student b on
a.id=b.teacherId
WHERE a.id = #{id:BIGINT}
</select>
<!-- userGeneratedKeys和keyProperty属性可以让插入后对象获得本身自己的id -->
<insert id="insertOneTeacher" parameterType="TeacherAlias" useGeneratedKeys="true" keyProperty="id">
insert into teacher (name,course) values(#{name},#{course})
</insert>
</mapper>
Student.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.gusi.demo.idao.IStudent">
<!-- 学生结果集合映射, -->
<resultMap type="StudentAlias" id="StudentResult">
<id column="sid" jdbcType="BIGINT" property="id" />
<result column="sname" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="TINYINT" property="sex" />
<result column="teacherId" jdbcType="BIGINT" property="teacherId" />
<!-- 多对一关系的时候,多方使用association标签映射一方,属性就是Student对象中定义的Teacher属性的名称。因为是对象类型,所以不能再直接使用column属性,需要使用另一个映射对象结果集合,该结果集合也是通过namespace.id指定。当然也可以不引用其他结果集合,在标签内部可以自己在定义临时的resultMap标签对象,比如id标签,result标签 -->
<association property="teacher"
resultMap="com.gusi.demo.idao.ITeacher.TeacherResult"></association>
</resultMap>
<!-- 查询学生基本信息,并且返回包含老师对象的信息 -->
<select id="queryOneStudent" parameterType="long" resultMap="StudentResult">
<!--在连接表查询的时候, 一定要注意这里的别名,不然会冲突 -->
SELECT a.id sid,a.name sname,a.sex,a.teacherId,b.id,b.name,b.course
FROM student a join teacher b on a.teacherId = b.id
WHERE a.id =
#{id:BIGINT}
</select>
<insert id="insertOneStudent" parameterType="com.gusi.demo.pojo.Student">
Insert into student
(name,sex,teacherId) values(#{name},#{sex},#{teacherId})
</insert>
<!-- 批量新增的时候,注意接收的对象是一个列表,需要在动态拼接sql的时候遍历参数集合对象 -->
<insert id="insertBatchStudent" parameterType="java.util.List">
Insert into student (name,sex,teacherId) values
<!-- 注意foreach的语法,集合直接写list字符串,用item表示当前遍历的对象,结果集合通过使用逗号分隔使用separator属性 -->
<foreach collection="list" item="item" separator=",">
(#{item.name},#{item.sex},#{item.teacherId})
</foreach>
</insert>
</mapper>
先只关注上面的select语句,insert语句是之后为了说明批量插入而写的。暂时先不需要关注insert语句
4、Mybatis全局配置文件中配置 数据库连接信息以及引入映射文件
mybatis-config.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>
<typeAliases>
<typeAlias alias="StudentAlias" type="com.gusi.demo.pojo.Student"/>
<typeAlias alias="TeacherAlias" type="com.gusi.demo.pojo.Teacher"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/gusi/demo/pojo/Student.xml"/>
<mapper resource="com/gusi/demo/pojo/Teacher.xml"/>
</mappers>
</configuration>
5、写接口查询
完成上面的配置以后,基本也就完成了一对多和多对一的所有配置,现在就是通过接口查询看是否符合我们预期。
//通过Id查询学生,会包含老师的对象信息
public Student queryOneStudent(Long id) {
Student student = null;
try {
sqlSession = mybatisUtils.getSqlSession();
IStudent iStudent = sqlSession.getMapper(IStudent.class);
//面向接口编程,调运queryOneStudent语句
student = iStudent.queryOneStudent(id);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
return student;
}
//通过Id查询老师,不会包含老师的所有学生集合信息,只有老师的个人基本信息
public Teacher queryOneTeacher(Long id) {
Teacher teacher = null;
try {
sqlSession = mybatisUtils.getSqlSession();
ITeacher iTeacher = sqlSession.getMapper(ITeacher.class);
//面向接口编程,调运queryOneTeacher语句
teacher = iTeacher.queryOneTeacher(id);
} catch (IOException e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return teacher;
}
//通过Id查询老师,会包含老师的所有学生集合信息
public Teacher queryOneTeacherWithStudent(Long id) {
Teacher teacher = null;
try {
sqlSession = mybatisUtils.getSqlSession();
ITeacher iTeacher = sqlSession.getMapper(ITeacher.class);
//面向接口编程,调运queryOneTeacherWithStudent语句
teacher = iTeacher.queryOneTeacherWithStudent(id);
} catch (IOException e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return teacher;
}
6、测试查询
在测试之前,需要先向数据库中插入合适的数据,假设我的初始化数据如下:
INSERT INTO `mybatis`.`teacher` (`id`, `name`, `course`) VALUES ('1', 'ltt', 'english');
INSERT INTO `mybatis`.`teacher` (`id`, `name`, `course`) VALUES ('2', 'dyy', 'computer');
INSERT INTO `mybatis`.`student` (`id`, `name`, `sex`, `teacherId`) VALUES ('1', 'a', '0', '1');
INSERT INTO `mybatis`.`student` (`id`, `name`, `sex`, `teacherId`) VALUES ('2', 'b', '1', '2');
INSERT INTO `mybatis`.`student` (`id`, `name`, `sex`, `teacherId`) VALUES ('3', 'c', '1', '2');
INSERT INTO `mybatis`.`student` (`id`, `name`, `sex`, `teacherId`) VALUES ('4', 'd', '1', '1');
@Test
public void testQueryOneStudent() {
StudentDao dao = new StudentDao();
Student student = dao.queryOneStudent(1L);
System.out.println(student);
}
@Test
public void testQueryOneTeacher() {
TeacherDao dao = new TeacherDao();
Teacher teacher = dao.queryOneTeacher(1L);
System.out.println(teacher);
}
@Test
public void testQueryTeacherWithStudent() {
TeacherDao dao = new TeacherDao();
Teacher teacher = dao.queryOneTeacherWithStudent(1L);
System.out.println(teacher);
}
完成上面的查询操作以后,我们还有需求是添加老师的时候,同事批量添加老师所有的学生,简单除暴的放方法当然是先把老师信息添加到teacher表中,然后再遍历老师的所有的学生,同事查询刚刚老师的id然后循环调运添加学生的方法,一个一个的添加学生对象。但是这样肯定是不优雅的,效率方面会有很大的影响,所以我们可以使用sql批量添加的语法来用一句sql批量添加所有学生.
7、批量添加
//添加老师,
public int insertOneTeacher(Teacher teacher) {
int count = 0;
try {
sqlSession = mybatisUtils.getSqlSession();
ITeacher iTeacher = sqlSession.getMapper(ITeacher.class);
count = iTeacher.insertOneTeacher(teacher);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return count;
}
//批量添加学生
public void insertBatchStudent(List<Student> students) {
try {
sqlSession = mybatisUtils.getSqlSession();
IStudent iStudent = sqlSession.getMapper(IStudent.class);
iStudent.insertBatchStudent(students);
sqlSession.commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
8、测试批量插入
@Test
public void testInsertTeacherWithStudent() {
TeacherDao daoT = new TeacherDao();
StudentDao daoS = new StudentDao();
Teacher t = new Teacher();
t.setName("teacher1");
t.setCourse("ep");
daoT.insertOneTeacher(t);
//注意在Teacher.xml映射文件中的insertOneTeacher语句中加入两属性userGeneratedKeys和keyProperty,目的是让在添加对象后,自动将新加对象的Id给设置到上面的t(Teacher)对象中,方便在添加下面的Student对象的时候设置teacherId属性的值
Student s1 = new Student();
s1.setName("s1");
s1.setSex(false);
s1.setTeacherId(t.getId());
Student s2 = new Student();
s2.setName("s2");
s2.setSex(false);
s2.setTeacherId(t.getId());
daoS.insertBatchStudent(Arrays.asList(s1, s2));
//注意在批量添加Student对象的时候,出入的参数是集合类型的Student,同时Student对象已经把teacherId属性给赋值。
}