首先将mybatis的关联关系与hibernate的关联关系做对比:
hibernate的关联关系:
mybatis的关联关系比hibernate的关联关系简单些,就看下面的对比吧
今天需要使用的表有:订单表,订单项表,书籍表,书籍类别表,书籍类别中间表
一对多关联关系
generatorConfig.xml中增加相关表
<table schema="" tableName="t_hibernate_order" domainObjectName="Order"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_hibernate_order_item" domainObjectName="OrderItem"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_hibernate_book" domainObjectName="Hbook"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_hibernate_category" domainObjectName="Category"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_hibernate_book_category" domainObjectName="HbookCategory"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
在generatorConfig.xml页面运行上方mybatis-generator
创建实体类/映射/mapper接口
OrderVo 继承了Order的所有属性,最终查询的结果封装到OrderVo 里面
package com.zking.vo; import com.zking.model.Order; import com.zking.model.OrderItem; import java.util.ArrayList; import java.util.List; public class OrderVo extends Order { private List<OrderItem> orderItems = new ArrayList<>(); public List<OrderItem> getOrderItems() { return orderItems; } public void setOrderItems(List<OrderItem> orderItems) { this.orderItems = orderItems; } }
OrderItemVo 继承了OrderItem的所有属性,最终查询的结果封装到OrderItemVo 里面
package com.zking.vo; import com.zking.model.Order; import com.zking.model.OrderItem; /** * @author 小李飞刀 * @site www.javaxl.com * @company * @create 2019-09-24 11:05 */ public class OrderItemVo extends OrderItem { private Order order; public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
OrderMapper.xml
<!-- property:实体类属性 colum对应的是表字段--> <resultMap id="OrderVoMap" type="com.zking.vo.OrderVo" > <result property="orderId" column="order_id"/> <result property="orderNo" column="order_no"></result> <collection property="orderItems" ofType="com.zking.model.OrderItem"> <result property="orderItemId" column="order_item_id"></result> <result property="oid" column="oid"></result> <result property="productId" column="product_id"></result> <result property="quantity" column="quantity"></result> </collection> </resultMap> <sql id="Base_Column_List" > order_id, order_no </sql> <select id="queryOrderVoByOrderId" resultMap="OrderVoMap" parameterType="java.lang.Integer"> select * from t_hibernate_order o,t_hibernate_order_item oi where o.order_id = oi.oid and o.order_id = #{orderId