多表查询
在操作数据库中经常要进行多表查询,这时我们就需要在.xml中编写resultmap,以下是一个示例:
<resultMap id="productMap" type="com.xxx.xxx.entity.Product">
<id column="p_id" property="pId"/>
<result column="last_edit_time" property="lastEditTime"/>
...
<result column="estatus" property="eStatus"/>
<association property="productCategory" column="product_category_id"
javaType="com.imooc.o2o.entity.ProductCategory">
<id column="product_category_id" property="productCategoryId"/>
<result column="product_category_name" property="productCategoryName"/>
</association>
<association property="shop" column="shop_id"
javaType="com.xxx.xxx.entity.Shop">
<id column="shop_id" property="shopId"/>
<result column="owner_id" property="ownerId"/>
<result column="shop_name" property="shopName"/>
</association>
<collection property="productImgList" column="product_id"
ofType="com.xxx.xxx.entity.ProductImg">
<id column="product_img_id" property="productImgId"/>
<result column="detail_img" property="imgAddr"/>
...
<result column="product_id" property="productId"/>
</collection>
</resultMap>
association
association用于关联表,表示一对一或多对一。比如这里的Product对应ProductCategory与Shop。这product实体类中有productcategory与shop的属性,而productcategory与shop分别对应自己的表。
collection
collection字面意思就是集合,用于一对多。在这里,因为product类的属性有一个ListproductImgList,表示一对多,因此这里我们不能继续使用association,而是collection
注意
以上就是mybatis多表查询关于resultmap的知识,这里需要注意的是:
在resultmap、association、collection中类型的拼写分别对应着:type、javatype、oftype,不可混淆,不然会出现关联不匹配的错误