在MySQL中,我们经常需要处理一对多的情况,使用MyBatis中的高级映射就能够很好地处理这种情况。
创建学生表student
和教师表teacher
,并插入测试数据,在这里学生和老师是多对一的关系:
CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) 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(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) 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 ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');
mybatis-config.xml
<configuration>
<properties resource="db.properties" />
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/cap/dao/TeacherMapping.xml" >mapper>
<mapper resource="com/cap/dao/StudentMapping.xml" >mapper>
mappers>
configuration>
这里需要引用到db.properties
,里面存放连接数据库的相关信息
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=mysql
SqlSessionFactoryBuilder
读取mybatis-config.xml
配置文件后,构建SqlSessionFactory
,再编写一个获取·SqlSession·的方法public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream is = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
Student
和Teacher
public class Student {
private int id;
private String name;
//关联老师的id
private Teacher teacher;
}
public class Teacher {
private int id;
private String name;
}
public interface TeacherMapping {
}
public interface StudentMapping {
}
<mapper namespace="com.cap.dao.StudentMapping">
mapper>
<mapper namespace="com.cap.dao.TeacherMapping">
mapper>
整个的层级结构如下
6. 简单测试一下,利用注解在TeacherMapping
接口编写一个通过id
查询Teacher
的方法
public interface TeacherMapping {
@Select("SELECT * FROM teacher WHERE id = #{id}")
Teacher getTeacherById(int id);
}
编写测试方法
public class Test {
@org.junit.Test
public void test(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
TeacherMapping mapper = sqlSession.getMapper(TeacherMapping.class);
Teacher teacher = mapper.getTeacherById(1);
System.out.println(teacher);
sqlSession.close();
}
}
/**
Teacher{id=1, name='秦老师'}
*/
现在我们需要查询所有学生的信息,并且还要查询对应的老师的信息
public interface StudentMapping {
/**
* 获取学生的信息,以及对应的老师的信息
* @return
*/
List<Student> getStudent();
}
查询出来的结大概是这样子:
首先我们来讲解一下第一个思路——嵌套SELECT查询:
先查询所有学生的信息,再根据学生的tid,去寻找对应的老师
<select id="getStudent" resultMap="StudentTeacher">
SELECT * FROM student;
select>
<resultMap id="StudentTeacher" type="student">
<result column="id" property="id" />
<result column="name" property="name" />
<association property="teacher" column="tid" javaType="teacher" select="getTeacher" />
resultMap>
<select id="getTeacher" resultType="teacher">
SELECT * FROM teacher WHERE id = #{tid};
select>
resultMap
结果集映射其他都能明白,关键在于如何处理Student
中含有的Teacher
对象,这里我们需要使用
标签来处理,它将查询得到的字段tid
对应到Teacher
对象上,再通过引用另一个SELECT
查询,得到该tid
所对应的Teacher
对象。
注意type
和javaType
,他们用了别名student
和teacher
,分别代表实体类Student
和Teacher
,这个可以在mybatis-config.xml
中配置
<typeAliases>
<package name="com.cap.pojo"/>
typeAliases>
编写一个测试方法
@org.junit.Test
public void test1(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
StudentMapping mapper = sqlSession.getMapper(StudentMapping.class);
List<Student> list = mapper.getStudent();
for(Student student : list){
System.out.println(student);
}
sqlSession.close();
}
查询结果如下:
Student{id=1, name='小明', teacher=Teacher{id=1, name='秦老师'}}
Student{id=2, name='小红', teacher=Teacher{id=1, name='秦老师'}}
Student{id=3, name='小张', teacher=Teacher{id=1, name='秦老师'}}
Student{id=4, name='小李', teacher=Teacher{id=1, name='秦老师'}}
Student{id=5, name='小王', teacher=Teacher{id=1, name='秦老师'}}
<resultMap id="StudentTeacher" type="student" >
<result property="id" column="sid" />
<result property="name" column="sname" />
<association property="teacher" javaType="teacher">
<result property="name" column="tname" />
association>
resultMap>
测试方法得到:
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='秦老师'}}
集合和关联非常相似,也是有嵌套 Select 查询和嵌套结果映射,这里只举嵌套结果映射的例子。
首先我们先修改实体类
public class Student {
private int id;
private String name;
private int tid;
}
public class Teacher {
private int id;
private String name;
private List<Student> students;
在接口TeacherMapping
中添加一个方法,用于查询指定id
的Teacher
public interface TeacherMapping {
Teacher getTeacherById(@Param("tid") int tid);
}
<mapper namespace="com.cap.dao.TeacherMapping">
<select id="getTeacherById" resultMap="TeacherStudent">
SELECT
s.id sid,
s.name sname,
t.name tname,
t.id tid
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" />
<collection property="students" ofType="com.cap.pojo.Student">
<result property="id" column="sid" />
<result property="name" column="sname" />
<result property="tid" column="tid" />
collection>
resultMap>
mapper>
ofType
:用于指定集合中的类型