mybatis collection多层嵌套 (三层嵌套)
mybatis 的collection 可以自动把查询结果转成一对多的对象结构,但是经测试只支持两层的结构,第三次并没有自动装配进去,所以采取这种办法,把其中一层拆出来先。
坑:我这里要往下传的参数 id 的类型是UUID ;model 里定义的是string 类型,但是在mybatis的查询查询过程中,它会去找java.util.uuid 这个类型,找不到所以就会报错,所以我在第一层的select里强制转换成varchar ,后续使用中再转回来
文字解说一下:
java那边请求findProductById(string id) 把id传到下面同名的select 里,这个select的resultMap是product ;
product 里面嵌套了子查询get-specs,最底下的查询get-specs的参数#{id}::uuid 就是主表查到的ID,并且由 column=”id” 这个配置决定
<resultMap id="product"
type="net.x.model.Product">
<id property="id" column="id" />
<result property="name" column="name" />
<collection property="specs" column="id" ofType="net.x.model.Specification" select="get-specs" />
</resultMap>
<!-- 这里的ID 是从java的mapper那里传过来的 -->
<select id="findProductById" resultMap="product">
select
p.id::varchar ,p.name
from product p
where p.flag != 'p' and p.id = #{id}::uuid
</select>
<!-- 这里用了一个list嵌套 ,为什么一开始不直接这样写呢,因为mybatis自动装配只能搞两层,我这个加起来三层了,所以只能分一层出来用select处理,你喜欢的话全部用select也行 -->>
<resultMap id="specs" type="net.x.model.Specification">
<id property="id" column="specification_id" />
<result property="name" column="specification_name" />
<collection property="options" ofType="net.x.model.SpecificationOption" javaType="list">
<id property="id" column="specification_option_id" />
<result property="value" column="specification_option_value" />
</collection>
</resultMap>
<!--这个id是 最上面的resultMap里的collection标签里的column属性,把第一层查询的id作为参数带下来 -->
<select id="get-specs" resultMap="specs">
select
s.id as specification_id , s.name as specification_name
,so1.id as specification_option_id , so1.value as specification_option_value
from ps
LEFT JOIN s on s.id = ps.specification_id
LEFT join so1 on so1.specification_id = s.id
where ps.product_id = #{id}::uuid
</select>
还没有评论,来说两句吧...