mybatis多表联查 ResultMap结果映射


<!-- 多表联查 -->
<select id="selectGoodsMap" resultType="java.util.LinkedHashMap">
    select g.*, c.category_name from t_goods as g, t_category as c
    where g.category_id = c.category_id
</select>

ResultMap结果映射,LinkedHashMap虽然将按数据库字段顺序来存在数据,但是缺点是不能像Java实体类一样存储数据。而ResultMap可以将查询结果映射为复杂类型的Java对象,并且支持对象关联查询等高级特训,非常适用于Java对象保存多表联查的结果

我们将两个表的进行关联查询t_category和t_goods

创建GoodsDTO.java来接收多表联查的数据
// Data Transfer Object 数据传输对象
public class GoodsDTO {
    private Goods goods = new Goods();
    private Category category = new Category();
    private String test;
 
    public Goods getGoods() {
        return goods;
    }
 
    public void setGoods(Goods goods) {
        this.goods = goods;
    }
 
    public Category getCategory() {
        return category;
    }
 
    public void setCategory(Category category) {
        this.category = category;
    }
 
    public String getTest() {
        return test;
    }
 
    public void setTest(String test) {
        this.test = test;
    }
 
    @Override
    public String toString() {
        return "GoodsDTO{" +
                "goods=" + goods +
                ", category=" + category +
                ", test='" + test + '\'' +
                '}';
    }

}

<!-- 结果映射 -->
    <resultMap id="rmGoods" type="com.lx.dto.GoodsDTO">
        <!-- property属性名(指向GoodsDTO中的某一个属性) colum字段名(查询结果中某个字段的名字) id是主键
            设置主键字段与属性映射-->

        <id property="goods.goodsId" column="goods_id"></id>
        <!-- 设置非主键字段与属性映射 -->
        <result property="goods.title" column="title"></result>
        <result property="goods.originalCost" column="original_cost"></result>
        <result property="goods.currentPrice" column="current_price"></result>
        <result property="goods.discount" column="discount"></result>
        <result property="goods.isFreeDelivery" column="is_free_delivery"></result>
        <result property="goods.categoryId" column="category_id"></result>
        <result property="category.categoryId" column="category_id"></result>
        <result property="category.categoryName" column="category_name"></result>
        <result property="category.parentId" column="parent_id"></result>
        <result property="category.categoryLevel" column="category_level"></result>
        <result property="category.categoryOrder" column="category_order"></result>
        <result property="test" column="test"></result>
    </resultMap>
    <select id="selectGoodsDTO" resultMap="rmGoods">
        select g.*,c.*,'1' as test from t_goods as g, t_category as c
        where g.category_id = c.category_id
    </select>
 

/**
 * 多表联查
 */
 @Test
 public void selectGoodsDTO(){
    SqlSession sqlSession = JdbcUtil.getSqlSession();
    List<GoodsDTO> map = sqlSession.selectList("goods.selectGoodsDTO");
    for(GoodsDTO g : map){
       System.out.println(g);
    }
}

猜你喜欢

转载自blog.csdn.net/whb008/article/details/107505467