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 一對一、一對多和多對多查詢,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
SpringBoot如何優(yōu)雅地使用Swagger2
這篇文章主要介紹了SpringBoot如何優(yōu)雅地使用Swagger2,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07
SpringBoot實現(xiàn)事務鉤子函數(shù)的示例
本文主要介紹了SpringBoot實現(xiàn)事務鉤子函數(shù)的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-08-08

