一、应用场景
一个产品(珀莱雅护肤品套装),由多个小瓶装商品(保湿霜、润肤乳、洗面奶....)构成,我们将用二级树形结构将数据查询出来。
数据结构如下:
{
"msg":"success",
"code":0,
"ProductList":[
{
"pid":1,
"name":"珀莱雅护肤品套装",
"maketPrice":199,
"sysModuleList":[
{
"id":1,
"moudleName":"保湿霜",
"moduleCode":"001"
},
{
"id":2,
"moudleName":"润肤乳",
"moduleCode":"002"
},
{
"id":3,
"moudleName":"洗面奶",
"moduleCode":"003"
}
]
},
{
"pid":2,
"name":"玉兰油护肤品套装",
"maketPrice":299,
"sysModuleList":[
{
"id":4,
"moudleName":"去痕霜",
"moduleCode":"004"
},
{
"id":5,
"moudleName":"洁面奶",
"moduleCode":"005"
},
{
"id":6,
"moudleName":"皱纹霜",
"moduleCode":"006"
}
]
}
]
}
二、代码实现:
1、首先建立产品(ProductEntityVo)和模块(也就是产品下的小商品,SysModuleEntity)的实体
ProductEntityVo:
public class PadProductEntityVo
{
private Integer pid;
private String name;
private Float maketPrice;
private List<SysModuleEntity> sysModuleList;
get,set......
}
SysModuleEntity:
@TableName("sys_module")
public class SysModuleEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId
private Integer id;
/**
* 模块名称
*/
private String moudleName;
/**
* 模块标识
*/
private String moduleCode;
get,set......
}
2、建好实体后建立一对多的xml配置(这里的查询语句是有个中间表做连接查询的。)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.purete.service.mapper.app.ProductDao" >
<resultMap id="BaseResultMap" type="com.purete.api.entity.app.ProductEntityVo" >
<id column="pid" property="pid" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="maket_price" property="maketPrice" jdbcType="REAL" />
<collection property="sysModuleList" ofType="com.purete.api.entity.sys.SysModuleEntity">
<result column="id" property="id" />
<result column="moudle_name" property="moudleName" />
<result column="module_code" property="moduleCode" />
</collection>
</resultMap>
<!--查询语句、自动映射到ProductEntityVo实体中-->
<select id="queryList" resultMap="BaseResultMap">
SELECT a.id as pid,a.name,a.maket_price,c.id as id,c.moudle_name,c.module_code from pad_product a,pad_product_module b,sys_module c WHERE a.id=b.goods_id AND b.module_id=c.id
</select>
</mapper>
3、dao中查询方法
@Mapper
public interface AppPadProductDao
{
//微信浏览商品信息
List<PadProductEntityVo> queryList();
}