mybatis 一对一、一对多和多对多查询实例代码
更新时间:2018年06月08日 10:05:07 作者:程序yuan
这篇文章主要介绍了mybatis 一对一、一对多和多对多查询的实例代码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
关键字:association 一对一映射(一个班级只有一个班主任)
<select id="getClass" parameterType="int" resultMap="ClassesResultMap"> select * from class c,teacher t where c.teacher_id=t.t_id and c.c_id=#{id} </select> <resultMap type="com.lcb.user.Classes" id="ClassesResultMap"> <id property="id" column="c_id"/> <result property="name" column="c_name"/> <association property="teacher" javaType="com.lcb.user.Teacher"> <id property="id" column="t_id"/> <result property="name" column="t_name"/> </association> </resultMap>
关键字:collection 一对多映射(一个老师有多个学生)
<resultMap type="Teacher" id="teacherMaps"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="class_name" property="className"/> <collection property="students" ofType="Student" select="getStudents" column="id"> </collection> </resultMap> <!-- 查询所有的老师级各自的所有学生 --> <select id="getAllTeacher" parameterType="Teacher" resultMap="teacherMaps"> SELECT t.id, t.NAME, t.class_name FROM teacher t </select> <select id="getStudents" parameterType="int" resultType="Student"> select s.id, s. NAME, s.class_name as className from student s where teacher_id = #{id} </select>
关键字:association 多对一映射(多个人属于一个国家)
多对一相当于一对多,也可以使用collection
<select id="selectCountry" resultType="Country"> select cid,cname from country where cid=#{ooo} </select> <resultMap type="People" id="peopleMapper2"> <id column="pid" property="pid"/> <result column="pname" property="pname"/> <association property="country" javaType="Country" select="selectCountry" column="countryId" /> </resultMap> <select id="selectById2" resultMap="peopleMapper2"> select pid,pname,countryId from people where pid = #{xxx} </select>
总结
以上所述是小编给大家介绍的mybatis 一对一、一对多和多对多查询,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
相关文章
详解MyBatis-Puls中saveBatch批量添加慢的问题
本文主要介绍了详解MyBatis-Puls中saveBatch批量添加慢的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-01-01Java CopyOnWriteArrayList源码超详细分析
为了将读取的性能发挥到极致,jdk中提供了CopyOnWriteArrayList类,下面这篇文章主要给大家介绍了关于java中CopyOnWriteArrayList源码解析的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下2022-11-11
最新评论