自定义Mapper完成业务要求

89 阅读1分钟

在需要进行多表之间的关联查询的时候,自动生成的通用Mapper,没有办法做到这一点,这时候我们需要自定义相关Mapper进行查询,即新建自定义Mapper及Mapper.xml文件。

import java.util.List;
//这里不需要再继承通用Mapper,即不需要写 extends MyMapper<Category>
public interface CategoryMapperCustom {
    public List getSubCatList(Integer rootCatId);
}
<?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.imooc.mapper.CategoryMapperCustom" >
    <resultMap id="myCategoryVO" type="com.imooc.pojo.vo.CategoryVO" >
        <id column="id" property="id"/>
        <result column="name" property="name" />
        <result column="type" property="type" />
        <result column="fatherId" property="fatherId" />
        <collection property="subCatList" ofType="com.imooc.pojo.vo.SubCategoryVo">
            <id column="subId" property="subId"/>
            <result column="subName" property="subName" />
            <result column="subType" property="subType" />
            <result column="subFatherId" property="subFatherId" />
        </collection>
    </resultMap>
    <select id="getSubCatList" parameterType="Integer" resultMap="myCategoryVO">
        SELECT  f.id as id,
                f.name as `name`,
                f.type as type,
                f.father_id as fatherId,
                c.id as subId,
                c.`name` as subName,
                c.type as subType,
                c.father_id as subFatherId
        FROM
            category f
        LEFT JOIN
            category c
        ON
            f.id = c.father_id
        WHERE
            f.father_id = #{rootCatId}
    </select>
</mapper>
// 对应实体类
import java.util.List;

public class CategoryVO {
    private Integer id;
    private String name;
    private String type;
    private Integer fatherId;
    private List<SubCategoryVo> subCatList;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Integer getFatherId() {
        return fatherId;
    }

    public void setFatherId(Integer fatherId) {
        this.fatherId = fatherId;
    }

    public List<SubCategoryVo> getSubCatList() {
        return subCatList;
    }

    public void setSubCatList(List<SubCategoryVo> subCatList) {
        this.subCatList = subCatList;
    }
}