之前在重温mybatis框架,嵌套查询和嵌套结果两种方式时,发现嵌套结果方式查询一对多时,List集合内只有一条数据,思来想去是不是SQL语句写错了,发现不是;而是在编写ResultMap标签时,针对映射方面出现了偏差;
之前的代码如下:
<mapper namespace="com.xja.mybatis.mapper2.CategoryMapper"> <resultMap id="CategoryWithProductResult" type="Category"> <id property="id" column="id"></id> <result property="typename" column="typename"></result> <collection property="productList" ofType="Product2"> <id property="id" column="id"></id> <result property="goodsname" column="goodsname"></result> <result property="price" column="price"></result> </collection> </resultMap> <select id="findCategoryWithProduct" resultMap="CategoryWithProductResult"> select c.*,p.id,p.goodsname,p.price,p.category_id from category c inner join product p on c.id = p.category_id where c.id = #{id} </select> </mapper>
运行结果:
更改如下:
运行结果如下:
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2f7c2f4f]
==> Preparing: select c.*,p.id as pid,p.goodsname,p.price,p.category_id from category c inner join product p on c.id = p.category_id where c.id = ?
==> Parameters: 2(Integer)
<== Columns: id, typename, pid, goodsname, price, category_id
<== Row: 2, 白色家电, 2, 冰箱, 4000.0, 2
<== Row: 2, 白色家电, 3, 空调, 5000.0, 2
<== Row: 2, 白色家电, 4, 洗衣机, 2000.0, 2
<== Total: 3
Category(id=2, typename=白色家电, productList=[Product2(id=2, goodsname=冰箱, price=4000.0), Product2(id=3, goodsname=空调, price=5000.0), Product2(id=4, goodsname=洗衣机, price=2000.0)])
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2f7c2f4f]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@2f7c2f4f]
Returned connection 796667727 to pool.
Process finished with exit code 0