MyBatis之——关联关系

1. MyBatis关联查询

1.1. MyBatis一对多关联查询

<!--一对多-->
<resultMap id="myStudent1" type="student1">
    <id property="sid" column="sid"/>
    <result property="sname" column="sname"/>
    <result property="sex" column="sex"/>
    <result property="sage" column="sage"/>
    <collection property="list" ofType="teacher">
        <id property="tid" column="tid"/>
        <result property="tname" column="tname"/>
        <result property="tage" column="tage"/>
    </collection>
</resultMap>

<!--一对多-->
<select id="find1" resultMap="myStudent1">
    select  *  from  student1  s  left  join  teacher  t  on s.sid=t.sid
</select>

 1.2. MyBatis多对一关联查询

<!--多对一-->
<resultMap id="myTeacher" type="teacher">
    <id property="tid" column="tid"/>
    <result property="tname" column="tname"/>
    <result property="tage" column="tage"/>
    <association property="student1" javaType="Student1">
        <id property="sid" column="sid"/>
        <result property="sname" column="sname"/>
        <result property="sex" column="sex"/>
        <result property="sage" column="sage"/>
    </association>
</resultMap>


<!--多对一-->
<select id="find2" resultMap="myTeacher">
select  *  from  teacher  t right join student1 s on  t.sid=s.sid
</select>

 

 1.3. MyBatis多对多关联查询

<!--多对多 以谁为主表查询的时候,主表约等于1的一方,另一方相当于多的一方-->
<select id="find3" resultMap="myStudent1">
    select  *  from  student1 s  left join relevance r on  s.sid=r.sid  left join teacher t on  r.tid=t.tid
</select>

2.综合示例

1. 准备

通过脚本创建相关的数据表:一对多(db1-n.txt)

2. 一对多关联查询

2.1 创建Model

创建Customer及Order表对应的model

在model中建立一对多关联关系在Customer中声明

private List<TOrderEntity> orders = new ArrayList<>();

注意:生成对应的getter/setter方法

2.2 创建Mapper层

1)定义接口

1)编写关联查询的sql语句

select t1.customer_id,t1.customer_name, t2.order_id, t2.order_nofrom t_customer t1 inner join t_order t2 on t1.customer_id = 
t2.cid

2)创建xml配置文件

2.3 创建service层

创建service层接口及其实现类,实现类的定义如下

2.4 创建测试类进行测试

测试通过一对多的关联关系就完成了。

3. 多对一关联关系

1)mapper接口

2)mapperXml

3)service层

4)测试

4. 多对多

两个一对多
1)创建需要的表结构
脚本dbn-n.txt,包括表结构及测试数据

2) model

 

3)mapper

 

4)service

5)测试

注:以上为news到category的一对多关联, 从category到new是的一对多关联的方式是一样的,只是sql及映射部分的具体配置不同。

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值