mybatis中的多表联查(第一步先通过仓库的id获取仓库数据,第二部通过在仓库数据中包含的商品id查询出商品的数据)

发布时间 2023-09-12 09:00:09作者: 努力是一种常态

2023-09-12

仓库

StoreHouseMapper

/**
     * 分步查询
     * 首先通过仓库的id查询出仓库
     */
    StoreHouse getSHAndGoodsByStepOne(@Param("id")Integer id);

StoreHouseMapper.xml

    <resultMap id="getSHAndGoodsByStepOneRM" type="StoreHouse">
        <id column="id" property="id"/>
        <result column="s_name" property="sName"/>
        <result column="s_type" property="sType"/>
        <result column="s_description" property="sDescription"/>
        <association property="goods"
                     select="com.hh.mapper.GoodsMapper.getSHAndGoodsByStepTwo"
                        column="g_id">

        </association>
    </resultMap>

    <select id="getSHAndGoodsByStepOne" resultMap="getSHAndGoodsByStepOneRM">
        select * from t_storehouse where id = #{id}
    </select>

商品

GoodsMapper

 /**
     * 分步查询第二步
     * 通过获取的仓库id获取商品数据
     */
    Goods getSHAndGoodsByStepTwo(@Param("gId")Integer gId);

GoodsMapper.xml

<select id="getSHAndGoodsByStepTwo" resultType="Goods">
        select * from t_goods where g_id=#{gId}
</select>

测试

@Test
    public void testSelectByStep(){
        SqlSession sqlSession = SqlSessionUtils.getSqlSession();
        StoreHouseMapper mapper = sqlSession.getMapper(StoreHouseMapper.class);
        StoreHouse storeHouse = mapper.getSHAndGoodsByStepOne(3);
        System.out.println(storeHouse);
        sqlSession.close();
    }

查询数据(测试数据)