第三节 对多
1、创建Mapper接口
public interface CustomerMapper {
Customer selectCustomerWithOrderList(Integer customerId);
}
2、创建CustomerMapper.xml配置文件
注意:不要忘记在Mybatis全局配置文件中注册
3、配置关联关系和SQL语句
<!-- 映射Customer本身的属性 --><br /> <id column="customer_id" property="customerId"/><br /> <result column="customer_name" property="customerName"/>
<!-- collection标签:映射“对多”的关联关系 --><br /> <!-- property属性:在Customer类中,关联“多”的一端的属性名 --><br /> <!-- ofType属性:集合属性中元素的类型 --><br /> <collection property="orderList" ofType="com.atguigu.mybatis.entity.Order"><br /> <!-- 映射Order的属性 --><br /> <id column="order_id" property="orderId"/><br /> <result column="order_name" property="orderName"/>
</collection>
对应关系可以参考下图:
4、junit测试
@Test
public void testRelationshipToMulti() {
CustomerMapper customerMapper = session.getMapper(CustomerMapper.class);
// 查询Customer对象同时将关联的Order集合查询出来<br /> Customer customer = customerMapper.selectCustomerWithOrderList(1);
System.out.println("customer.getCustomerId() = " + customer.getCustomerId());<br /> System.out.println("customer.getCustomerName() = " + customer.getCustomerName());
List<Order> orderList = customer.getOrderList();<br /> for (Order order : orderList) {<br /> System.out.println("order = " + order);<br /> }
}
5、关键词
在“对多”关联关系中,同样有很多配置,但是提炼出来最关键的就是:“collection”和“ofType”