回顾SQL99中的连接查询
一对一
<mapper namespace="cardNamespace"> <resultMap type="cn.itcast.javaee.mybatis.one2one.Card" id="cardMap"> <id property="id" column="id" /> <result property="num" column="num" /> </resultMap> </mapper> <mapper namespace="studentNamespace"> <resultMap type="cn.itcast.javaee.mybatis.one2one.Student" id="studentMap"> <id property="id" column="id" /> <result property="name" column="name"/> <association property="card" resultMap="cardNamespace.cardMap"/> </resultMap> <select id="findById" parameterType="int" resultMap="studentMap"> select s.id,s.name,c.id,c.num from students s inner join cards c on s.cid = c.id and s.id = #{id} </select> </mapper>
一对多
<mapper namespace="gradeNamespace"> <resultMap type="cn.itcast.javaee.mybatis.one2many.Grade" id="gradeMap"> <id property="id" column="gid" /> <result property="name" column="gname"/> <collection property="studentList" resultMap="studentNamespace.studentMap"/> </resultMap> <select id="findGradeByName" parameterType="string" resultMap="gradeMap"> select g.gid,g.gname,s.sid,s.sname from grades g,students s where g.gid = s.sgid and s.sname = #{name} </select> </mapper>
<mapper namespace="studentNamespace"> <resultMap type="cn.itcast.javaee.mybatis.one2many.Student" id="studentMap"> <id property="id" column="sid" /> <result property="name" column="sname"/> <association property="grade" resultMap="gradeNamespace.gradeMap"/> </resultMap> <select id="findAllByName" parameterType="string" resultMap="studentMap"> select s.sid,s.sname,g.gid,g.gname from grades g,students s where g.gid = s.sgid and g.gname = #{name} </select> </mapper>
多对多
<mapper namespace="studentNamespace"> <resultMap type="cn.itcast.javaee.mybatis.many2many.Student" id="studentMap"> <id property="id" column="sid" /> <result property="name" column="sname"/> </resultMap> <select id="findStudentByName" parameterType="string" resultMap="studentMap"> select s.sid,s.sname from students s,middles m,courses c where s.sid = m.sid and m.cid = c.cid and c.cname = #{name} </select> </mapper>
<mapper namespace="courseNamespace"> <resultMap type="cn.itcast.javaee.mybatis.many2many.Course" id="courseMap"> <id property="id" column="cid" /> <result property="name" column="cname"/> </resultMap> <select id="findCourseByName" parameterType="string" resultMap="courseMap"> select c.cid,c.cname from students s,middles m,courses c where s.sid = m.sid and m.cid = c.cid and s.sname = #{name} </select> </mapper>
原文地址:https://www.cnblogs.com/escapist/p/9046368.html
时间: 2024-10-19 09:19:57