一、什么是关联关系?
关联关系是指类之间的引用关系,如果类A与类B关联,那么类A将被定义成类B的属性。
例如:
public class Address{
private String name;
}
public class B{
private String sid;
private Float score;
private Address address;
}
二、关联关系的分类
1、一对一,一个人只能有一张身份证,而一张身份证只能属于一个人;
2、一对多,一个客户对应多个订单
3、多对一:一种书本类型对应多本数,例如:神话 -> 西游记、山海经、聊斋志异
4、多对多,一篇新闻对应多种类型,一种类型对应多篇新闻(永远视为两个一对多)
三、一对多和多对一
1、按照上举例的客户和订单的关系创建如下两张表
t_customer(客户)
t_order(订单)
使用逆向工程自动创建实体类和mapper层接口和mapper映射文件
3.1 一对多
定义方法
List<Customer> queryAll();
定义关联关系和编写sql
<!--定义关联关系-->
<resultMap id="onToManey" type="com.zking.model.Customer">
<id column="customer_id" property="customerId"/>
<result column="customer_name" property="customerName" />
<!--注入多方属性-->
<collection property="listOrder" ofType="com.zking.model.Order">
<id column="order_id" property="orderId"/>
<result column="order_no" property="orderNo"/>
<result column="cid" property="cid"/>
</collection>
</resultMap>
<select id="queryAll" resultMap="onToManey">
select * from t_customer c
left join t_order o
on c.customer_id = o.cid
</select>
测试
package com.zking.service.impl;
import com.zking.model.Customer;
import com.zking.service.ICustomerService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import static org.junit.Assert.*;
public class CustomerServiceImplTest extends BaseTest{
@Autowired
private ICustomerService customerService;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void queryAll() {
List<Customer> customerList = customerService.queryAll();
customerList.forEach(System.out::println);
}
}
3.2 多对一
定义方法
Order queryOrderByOrderId(Integer orderId);
定义关联关系和编写sql
<!--定义关联关系映射-->
<resultMap id="manyToOne" type="com.zking.model.Order">
<id column="order_id" property="orderId"/>
<result column="order_no" property="orderNo"/>
<result column="cid" property="cid"/>
<!--注入一方:客户-->
<association property="customer" javaType="com.zking.model.Customer">
<id column="customer_id" property="customerId"/>
<result column="customer_name" property="customerName"/>
</association>
</resultMap>
<select id="queryOrderByOrderId" resultMap="manyToOne">
select * from t_order o
inner join t_customer c
on o.cid = c.customer_id
where o.order_id = #{orderId}
</select>
测试
package com.zking.service.impl;
import com.zking.model.Order;
import com.zking.service.IOrderService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.*;
public class OrderServiceImplTest extends BaseTest{
@Autowired
private IOrderService orderService;
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void queryOrderByOrderId() {
System.out.println(orderService.queryOrderByOrderId(1));
}
}