Mabatis映射文件中的association标签联合select属性的使用

先来看一段映射文件 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lkd.dao.RegionDao">

    <!-- 通用查询映射结果 -->
    <resultMap id="regionMap" type="com.lkd.entity.RegionEntity" autoMapping="true">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="remark" property="remark" />
        <association property="nodeCount" column="id"  select="com.lkd.dao.NodeDao.selectCountByRegionId"></association>
    </resultMap>

</mapper>

resultMap标签的作用在这里就不多说了

我们来回顾一下association标签的作用:

 配置关联对象的映射关系 , 一般与resultMap标签联合使用

怎么理解这句话呢?

association(一对一):映射到JavaBean的某个“复杂类型”属性,比如JavaBean类,即JavaBean,即JavaBean内部嵌套一个复杂数据类型(JavaBean)属性,这种情况就属于复杂类型的关联。但是需要注意:association仅处理一对一的关联关系。

而在这里,它并不是映射了一个复杂类型的属性,看下该xml文件所对应的实体类

@Data
@TableName(value = "tb_region",autoResultMap = true,resultMap = "regionMap")
public class RegionEntity {
    @TableId(value = "id",type = IdType.ASSIGN_ID)
    private Long id;
    private String name;
    private String remark;
    @TableField(exist = false)//表示并非该表字段
    private Integer nodeCount;

    @TableField(exist = false)
    private List<NodeEntity> nodeList;
}

很明显,一个普通的包装类

那么这里的association什么意思呢?

以上Xml文件中<association>标签中 ,column属性中的id为本表字段id值,表示压入到select属性映射的SQL语句的输入参数中,而查询后的结果,将注入property代表的实体类中的属性中--nodeCount!

来看一下select属性后所映射xml中的SQL

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lkd.dao.NodeDao">

  <select id="selectCountByRegionId" resultType="integer">
    select IFNULL(COUNT(*),0) from tb_node where region_id=#{regionId}
  </select>

</mapper>

也就是说第一个xml中sql查到的id会通过association标签传入到第二个xml中的regionId中,然后查询到的结果,将注入到第一个xml中property所对应实体类的属性nodeCount中!

浅显理解,如有错误,恭候指正~