在MyBatis中,多表关系没有像Hibernate中体现的那么明显,关系型数据库表与表之间的关系主要有:
1、一对一关系
账户表-----账户详情表
2、多对一关系
学生和班级
3、一对多关系
班级和学生
4、多对多关系
学生和课程
而在myBatis中只需记得2个标签即可实现多表关系:
1、association标记一对一或多对一
association其实就是标记当前的属性是一个对象,一般可用于一对一或多对一
<!—实现两张表的一对一关系查询映射 --> <select id=”query” resultMap=”ws2”> select w.*,h.id husid,h.name hname,h,age hage from tb_wife w left join tb_husband h on w.hid=h.id </select> <resultMap type=”Wife” id=”ws2”> <id property=”id” column=”id”/> <result property=”name” column=”name”/> <result property=”hobby” column=”hobby”/> <!—嵌套对象,通过联结查询获取结果 --> <association property=”husband” javaType=”Husband”> <id property=”id” column=”husid”/> <result property=”name” column=”hname”/> <result property=”age” column=”hage”/> </association> </resultMap>
一对一可以,多对一一样,其中javaType标记的属性的数据类型,不可省略。
2、collection实现一对多或多对多
该标签标记当前属性是一个集合,内容通过SQL查询而来。
下面配置体现一对多的关系实现:
<select id=”query1” resultMap=”myhs2”> select h.*,c.id cid,c.name cname,c.infant from tb_husband h left join tb_child c on h.id=c.hid </select> <resultMap type=”Husband” id=”myhs2”> <id property=”id” column=”id”/> <result property=”name” column=”name”/> <result property=”age” column=”age”/> <!-- 嵌套集合--> <collection property=”childs” ofType=”Child”> <id property=”id” column=”cid”/> <result property=”name” column=”cname”/> <result property=”infant” column=”infant”/> </collection> <resultMap>
其中,ofType:为集合中泛型的数据类型,也就是多的一方对应的类名。
3、collection和association嵌套使用
这个标签可以嵌套在一起使用,一般用来表达多对多的关系映射中:
<select id=”query” parameterType=”int” resultMap=”mp1”> select s.*,st.id stid,st.days,t.id teaid,t.name tname from tb_student s left join tb_studentrelation st on s.id=st.sid left join tb_teacher t on t.id=st.tid where s.id=#{id} </select> <!-- 多对多的中间表的关系--> <resultMap type=”Student” id=”mp1”> <id property=”id” column=”id”/> <result property=”name” column=”name”/> <!--和中间表存在一对多--> <collection property=”list” ofType=”StudentRelation”> <id property=”id” column=”stid”/> <result property=”days” column=”days”/> <!-- 中间表和教师表存在多对一--> <association property=”teacher” javaType=”Teacher”> <id property=”id” column=”teaid”/> <result property=”name” column=”tname”/> </association> </collection> <resultMap>