Mybatis关联映射
在关系型数据库中,多表之间存在着三种关联关系:
一对一:在任意一方引入对方主键作为该表的外键
一对多:在“多”方添加“一”方主键作为外键
多对多:产生中间关系表,引入两端的表的主键作为外键,两个引入进来的主键组成一个联合主键或使用新的字段作为主键
在Java中,对应数据库里面的实体类可以这样表示:

一对一:在本类中定义对方类型的对象,如A类中定义B类类型的属性b,B类中定义A类类型的属性a;
一对多:一个A类类型对应多个B类类型的情况,需要在A类中以集合的方式引入B类类型的对象,在B类中定义A类类型的属性a;
多对多:在A类中定义B类类型的集合,在B类中定义A类类型的集合。
我们只需要在配置映射文件的时候,规定我们实体类中的变量类型就可以了。
如这里有一个课程表类,里面分别有对应的课程id,课程名称,还有这门课程学生考取的分数:
public class Course { private int cid; private String name; private List<Scores> scores; }
那我们在配置文件中就可以这样来映射它:
<resultMap type="person.clp.entity.Course" id="myResult"> <id property="cid" column="cid"/> <result property="name" column="name"/> <collection property="scores" ofType="person.clp.entity.Scores" column="cid" select="person.clp.dao.CourseDao.selectCourseById" /> </resultMap>
上面的collection代表的是List集合类型,如果你是一个对象的话,就得用到association标签
如我们这里有一个Score类(学生考某一门课的分数):
public class Scores { private int sid; private int cid; private int score; private Course course; }
那么我们在映射文件里就得用association去映射这个对象
<resultMap id="scoresMap" type="person.clp.entity.Scores"> <id property="sid" column="sid"></id><!--property对应实体类,column对应表中的列--> <id property="cid" column="cid"></id> <association property="student" javaType="person.clp.entity.Student" column="sid" select="person.clp.dao.StudentDao.selectStudentById" /> </resultMap>
<select id="selectByStudentId" resultMap="scoresMap">
select * from scores where sid = #{sid}
</select>

浙公网安备 33010602011771号