属性映射

在一些情况下数据库的记录和POJO对象无法直接映射,包括两种情形:

  • 数据库字段与POJO字段名称不同(可以避免);
  • 关联查询时,需要将关联表的数据映射为另一个类型的POJO(一对一),或List中(一对多);

在MyBatis中通过resultMap来完成自定义映射

7|11.自定义字段与属性映射

先将Products表中的字段更名为p_xxx,如下所示:

image-20191231144158478

<!--自定义映射关系 id:该映射关系的标识    type:映射到的POJO类型此处为别名-->
<resultMap id="product_resultMap" type="products">
    <!--主键-->
    <id column="p_id" property="pid"/>
    <!--其他字段-->
    <result column="p_name" property="pname"/>
    <result column="p_price" property="price"/>
    <result column="p_date" property="pdate"/>
    <result column="p_cid" property="cid"/>
</resultMap>
<!--引用映射关系-->
<select id="selectProductsCustomMapping" resultMap="product_resultMap">
    select *from products
</select>

原文地址:https://www.cnblogs.com/huaobin/p/14162734.html