mybatis多表联合查询

博客介绍了数据库查询中的一对一和一对多查询。一对一查询有两种方式,一是使用业务扩展类,用resultType指定类属性包含多表查询所有字段;二是将另一个类作为属性存在。还提及了一对多查询,但未展开说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一对一查询

方式一:使用业务扩展类(business)

写一个单独的类 继承一个类将其余的字段做属性(字段/属性唯一)

核心:用resultType指定类的属性 包含 多表查询的所有字段
<select id="queryByOO" resultType="org.zq.entity.PersonBusiness">
    select  * from person p,personjob j where p.job_id = j.id
 </select>

方式二:将另一个类作为属性存在

<select id="queryByMapOO" resultMap="queryByMap">
      select  *
      from person p inner join personjob j on p.job_id = j.id
   </select>
<resultMap id="queryByMap" type="org.zq.entity.Person">
      <id property="id" column="id"/>
      <result property="name" column="name"/>
      <result property="bookId" column="book_id"/>
      <!-- 一对一时,对象成员使用 association映射;javaType指定该属性的类型-->
      <association property="job" javaType="org.zq.entity.Job">
         <id property="id" column="id"/>
         <result property="name" column="name"/>
      </association>
</resultMap>

一对多

 <select id="queryO2M" resultMap="O2M" parameterType="int">
        SELECT c.*, s.* FROM  class c
                                  INNER JOIN stu s ON c.class_id = s.class_id
        WHERE  c.class_id  = #{id}
    </select>

一个班级中的学生

    <resultMap id="O2M" type="org.zq.entity.myClass">
        <id property="classId" column="class_id"></id>
        <result property="className" column="class_name"></result>
        <!-- 配置成员属性学生,一对多;属性类型:javaType,属性的元素类型ofType  可以级联配置-->
        <collection property="stuList" ofType="org.zq.entity.Stu">
            <id property="stuId" column="stu_id"></id>
            <result property="stuName" column="atu_name"></result>
            <result property="classId" column="class_id"></result>
      
      可以级联配置
      
        </collection>
    </resultMap>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值