龙空技术网

MyBatis 配置之集合的嵌套

发哥微课堂 109

前言:

现在我们对“pid算法嵌套”大致比较重视,大家都需要了解一些“pid算法嵌套”的相关资讯。那么小编同时在网络上汇集了一些关于“pid算法嵌套””的相关资讯,希望看官们能喜欢,姐妹们快快来了解一下吧!

点击右上角【关注】发哥微课堂头条号,get更多相关技能~

0x00:前言介绍

在一些查询结果包装类中,包含一些 List 集合属性,使用 collection 标签可以声明该 List 集合中属性的类型,便于 MyBatis 对包装类中的集合类型属性进行映射。

0x01:代码示例

例如商城,取出某一个商品信息以及该商品的评价列表,其中商品包装类 Product 的定义代码如下:

package cn.com.mybatis.pojo;

public class Product{

//商品id

private int pid;

//商品名称

private String pname;

//商品的评价信息

private List<Reply> replys;

//get和set方法

}

此时,商品的评价信息就是一个 List,所以在定义结果映射配置时,使用 collection 来定义评价结果集合,示例代码如下:

<resultMap id="productResult" type="cn.com.mybatis.pojo.Product">

<id property="pid" column="product_id"/>

<result property="pname" column="product_name"/>

<collection property="replys" select="queryReplyByProductId" column="product_id" ofType="Reply"/>

</resultMap>

<select id="queryProductInfo" parameterType="int" resultMap="productResult">

select

P.id as product_id,

P.name as product_name

from product P WHERE P.id = #{id}

</select>

<select id="queryReplyByProductId" parameterType="int" resultType="Reply">

select * from reply R WHERE R.pid = #{ProductId}

</select>

以上示例中,Product 与商品评价 Reply 会进行关联,一个商品评价 Reply 的 pid 只对应一个商品 Product 的 id,而一个商品 Product 的 id 可对应多个商品评价 Reply 的 pid,是一对多的关系。

通过配置集合的嵌套结果,就可以将查询结果中的包装类的集合类型的属性嵌套到结果集中。通过上面的配置最终得到一个包含 Reply 的 List 的商品包装类 Product。

0x02:外部引用

collection 标签也可以引入外部的 resultMap 配置。如果 queryReplyByProductId 配置的 sql 查询结果中使用了别名,或数据库字段名与 Reply 类属性名不对应,此时需要返回一个名为 replyResult 的 resultMap,那么 productResult 中的 collection 可以做如下配置:

<resultMap id="productResult" type="cn.com.mybatis.pojo.Product">

<id property="pid" column="product_id"/>

<result property="pname" column="product_name"/>

<collection property="replys" ofType="Reply" resultMap="replyResult" columnPrefix="reply_">

</resultMap>

<resultMap id="replyResult" type="Reply">

<id property="id" column="id"/>

<result property="username" column="username"/>

<result property="info" column="info"/>

</resultMap>

columnPrefix 代表为外部引入的 resultMap 中的每一个元素的 column 属性加上一个前缀。

0x03:总结

在一些查询结果包装类中,包含一些 List 集合属性,可使用 collection 标签声明该 List 集合中属性的类型。以便于 MyBatis 对包装类中的集合类型属性进行映射。可以在 collection 标签中配置,也可以引入外部的 resultMap 做配置。

标签: #pid算法嵌套