Mybatis的一对多和多对一关系

  1. 一对多

–注意事项,使用左外连接而非内连接
SELECT c., o.
from t_customer c left outer join t_order o on c.customer_id = o.cid
where c.customer_id = 4;

SELECT c., o.
from t_customer c inner join t_order o on c.customer_id = o.cid
where c.customer_id = 4;

  1. 多对一



     <!-- 多对一的关系 -->
     <!-- property: 指的是属性的值, javaType:指的是属性的类型-->
     <association property="customer" javaType="Customer">
         <id column="customer_id" property="customerId"/>
         <result column="customer_name" property="customerName"/>
     </association>
    

    为什么多对一可以使用内连接???
    select o., c.
    from t_order o inner join t_customer c on o.cid = c.customer_id
    where o.order_id = #{orderId,jdbcType=INTEGER}

  2. 多对多

SELECT n.news_id, n.title, c.category_id, c.category_name
FROM t_news n left outer join t_news_category nc on n.news_id = nc.nid left outer join t_category c on nc.cid = c.category_id
where n.news_id = #{newsId,jdbcType=INTEGER}

  1. 新闻添加或删除类别

  2. 新闻删除

  3. 作业
    多对多关系删除

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mybatis是一个优秀的持久层框架,它支持多种关系映射方式,包括一对一、一对多、多对一、多对多等。下面举一个一对多关系映射的例子: 假设我们有两个表:学生表(student)和课程表(course),一个学生可以选修多门课程,因此在课程表中需要保存学生的id。我们可以通过Mybatis进行一对多关系映射。 首先我们需要定义两个Java类:Student和Course,然后在Student类中定义一个List<Course>类型的属性,用于保存学生所选修的课程。在Course类中定义一个Student类型的属性,用于保存选修该课程的学生信息。 接下来,在Mybatis的Mapper.xml文件中编写SQL语句,可以使用Mybatis的association和collection标签来实现一对多关系映射。具体操作如下: 1. 首先查询学生表,将学生信息和对应的课程id一并查询出来。 2. 然后根据查询出来的课程id查询课程表,将查询出来的课程信息赋值给Course对象。 3. 将Course对象添加到List<Course>属性中。 4. 最后返回Student对象,即可完成一对多关系映射。 以下是Mapper.xml文件的示例代码: ``` <!-- 查询学生信息和对应的课程id --> <select id="getStudent" parameterType="int" resultType="Student"> SELECT * FROM student WHERE id = #{id} </select> <!-- 根据课程id查询课程信息 --> <select id="getCourseByStudentId" parameterType="int" resultType="Course"> SELECT * FROM course WHERE student_id = #{studentId} </select> <!-- 定义一对多关系映射 --> <resultMap id="studentMap" type="Student"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="age" property="age"/> <collection property="courses" ofType="Course"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="teacher" property="teacher"/> </collection> </resultMap> ``` 使用以上配置,在调用Mapper接口时,即可获取到包含学生信息和所选修的课程信息的Student对象。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值