有两张表:
学生表:
教师表:
其关联关系可表示为:
在一对多查询时(多个学生对应一个老师),可想到方法:
- 对结果集进行嵌套查询
将所需的教室和学生类构建好后,将mybatis核心配置完成后(所需的类和核心配置文件在文章末尾)
TeacherMapper.xml文件可进行查询:
<!-- 结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid, s.name sname,t.name tname, t.id tid
from mybatis.student s,mybatis.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="Student" >
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
对比一对多和多对一可了解到 :
在一对多时候用 association
在多对一时候用 collection
核心配置文件:
<?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>
<!-- 配置文件的实现-->
<properties resource="db.properties" />
<settings>
<!-- 标准的日志 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 别名扫描包-->
<typeAliases>
<package name="com.tang.pojo"/>
</typeAliases>
<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>
<package name="com.tang.dao" />
</mappers>
</configuration>
核心封装类:
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
Student类:
@Data
public class Student {
private int id;
private String name;
//一个老师拥有多个学生
private int tid;
}
Teacher类:
@Data
@ToString
public class Teacher {
private int id;
private String name;
//一个对应多个学生
private List<Student> students;
}
Tacher接口:
public interface TeacherMapper {
//获取老师
// List<Teacher> getTeacher();
//获取指定老师下的所有学生及老师信息
Teacher getTeacher(@Param("tid") int id);
}
测试类:
public class TeacherTest {
public static void main(String[] args) {
SqlSession sqlSession = MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
测试结果:
Teacher(id=1, name=秦老师, students=[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)])