1. 数据库表的设计
- 在我们的生活中有许多的关联关系,我们大致可以分为三类,一对一,一对多,多对多三种,在这里我们借助Mybatis较为详细的介绍一下,多对多的关联实现
- 我们这里就以简单的学生和课程之间的关系为例,使用mybatis来处理这个关联关系
- 首先是student数据表的设计,简单的id,sname,sex三个属性,再就是课程数据表的设计id,cname,在数据库中多对多的关系需要第三张表来维护两者之间的关系,这里为class表,属性为id,tid(外键,关联student的id属性),cid(外键,关联course的id属性)
2. 实体类的设计
- 在我们的生活中,基本上我们需要在查询学生信息的时候,他们选课的信息也要呈现出来,因为在实体类的设计上,我们必须拿到学生选课的course信息,因此我们student实体类的设计如下:
public class Student {
private Integer id;
private String name;
private String sex;
private List<Course> courseList;
//省略对应的set和get方法
}
- 对于课程表的设计没什么特别的,和数据表字段完全对应
public class Course {
private Integer id;
private String name;
//省略对应的set和get方法
}
3. Mapper.xml
- CourseMapper.xml
下面表示的这个select是根据学生的id查询课程信息,这样我们就可以知道某一个具体学生选了哪些课程,也是为后面的查询打下基础
<?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="xzw.dao.CourseMapper">
<select id="findCourseBySid" resultType="xzw.bean.Course">
select * from course where cid in (select cid from class where sid=#{sid})
</select>
</mapper>
注解版:
public interface CourseMapper {
@Select("select * from course where cid in (select cid from class where sid=#{sid})")
Course findCourseBySid(Integer sid);
}
- StudentMapper.xml
这个就是为了我们实体类封装信息做的结果映射,根据学生id,查询到该学生的所有信息,包括已选的课程,collection标签帮我们完成了某个学生具体选了哪些课程的封装,该语句的含义就是将数据库里面查询出来的id属性作为参数去进行select子标签里面语句的查询,并将结果以ofType标签里面对象的形式返回后填充到property这个实体类属性里面
<?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="xzw.dao.StudentMapper">
<select id="findStudentByid" resultMap="CourseMap">
select * from student where id = #{id}
</select>
<resultMap id="CourseMap" type="xzw.bean.Student">
<collection property="courseList" ofType="xzw.bean.Course" column="id" select="xzw.dao.CourseMapper.findCourseBySid"></collection>
</resultMap>
</mapper>
注解版:
public interface StudentMapper {
@Select("select * from student where id = #{id}")
@Results({
@Result(column = "id",property = "courseList",many = @Many(select = "xzw.dao.CourseMapper.findCourseBySid"))
})
Student findStudentByid(Integer id);
}