mybatis 一对一、一对多和多对多查询实例代码

2025-05-29 0 73

关键字:association 一对一映射(一个班级只有一个班主任)

?

1

2

3

4

5

6

7

8

9

10

11
<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 一对多映射(一个老师有多个学生)

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
<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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
<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 一对一一对多多对多查询,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:https://blog.csdn.net/weixin_38048680/article/details/80307466

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 mybatis 一对一、一对多和多对多查询实例代码 https://www.kuaiidc.com/111721.html

相关文章

发表评论
暂无评论