当前位置: 代码迷 >> Java相关 >> mybatis 地图per association collection
  详细解决方案

mybatis 地图per association collection

热度:124   发布时间:2016-04-22 19:11:02.0
mybatis mapper association collection

1.Question Description:

  sometimes, POJO bean contains another bean or collection as property,

  it's suitable for select data from more than one table.

2. Solution:

  2.1 mybatis mapper file , for example:

<mapper namespace="cn.net.syl.dao.ProductsMapper" >
  <resultMap id="BaseResultMap" type="cn.net.syl.model.Products" >
    <id column="product_id" property="productId" jdbcType="BIGINT" />
    <result column="product_name" property="productName" jdbcType="VARCHAR" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="descript" property="descript" jdbcType="VARCHAR" />
    <result column="price" property="price" jdbcType="DOUBLE" />
    ......
  </resultMap>

  .....

<resultMap type="cn.net.syl.model.Products" id="BigResultMap" extends="BaseResultMap">
        <association property="prodExt" javaType="cn.net.syl.model.ProductsExt">
           <id column="product_ext_id" property="productExtId" jdbcType="BIGINT" />
          <result column="product_id" property="productId" jdbcType="BIGINT" />
         ....
        </association>
        <collection property="prodPropImgList" ofType="cn.net.syl.model.ProductsPreviewImages">
               <id column="prev_id" property="prevId" jdbcType="BIGINT" />
            <result column="product_id" property="productId" jdbcType="BIGINT" />
            ..........
        </collection>
  </resultMap>

  <select id="getProductInfo" resultMap="BigResultMap" parameterType="java.lang.Long">
      select
     a.*, b.detail_descript,
     c.image_url,
     c.product_id,
     c.property_id,
     c.value_id,
     d.value_name
    FROM
     syl_products a,
     syl_products_ext b,
     syl_products_preview_images c,
     syl_property_values d
    where a.product_id = b.product_id
      and a.product_id = c.product_id
      and c.value_id = d.value_id
      and a.product_id = #{productId}
  </select>
</mapper>

  2.2  POJO bean , for example:

public class Products {
    
    private String idStr;
    
    private Long productId;

    private String productName;

    ............
    
    //add field for sql
    private ProductsExt prodExt;
    
    
    //add field for sql
    List<ProductsPreviewImages> prodPropImgList;
    
    //add field for sql
    private List<ProductPropertyEntity> baseProdPropList;

    //getter and setter method

    ....

}

  相关解决方案