1.设置数据库字段和数据
[{“id”: 101, “key”: “品牌”, “value”: “Apple/苹果”},
{“id”: 102, “key”: “型号”, “value”: “iphone 14 Pro Max”},
{“id”: 103, “key”: “版本”, “value”: “国行”}]
此为保存在数据库的json数据
2.定义对应的实体类
(1)定义json数组中的对象实体类
@Data
public class CategoryChildrenDto {
private String id;
private String pid;
private String name;
}
(2) 定义数据库映射实体类
private List<GoodsAttributes> attributes;//存储的是json数组,用list接收
3.在mapper.xml中定义resultMap
<resultMap id="GoodsDetailMap" type="com.tminto.domain.dto.GoodsDetailDto">
<id column="id" property="id"/>
<result property="sellerId" column="user_Id"/>
<result property="sellerName" column="username"/>
<result property="avatar" column="avatar"/>
<result property="goodsName" column="name"/>
<result property="price" column="price"/>
<result property="description" column="description"/>
<!--指定字段类型处理器为JacksonTypeHandler-->
<result property="attributes" column="attributes" typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler"/>
<result property="image" column="image"/>
<result property="number" column="number"/>
<result property="viewCount" column="view_count"/>
</resultMap>
4.自定义sql语句
指定resultMap
<select id="selectGoodsDetailById" resultMap="GoodsDetailMap">
select
g.id,
g.user_Id,
u.username,
u.avatar,
g.name,
g.price,
g.description,
g.attributes,<!--json字段-->
g.image,
g.number,
g.view_count
from goods g
join user u on g.user_id = u.id
where g.id = #{id}
</select>
5.调用方法
(1)调用接口
public GoodsDetailDto getGoodsInfo(String id) {
return baseMapper.selectGoodsDetailById(id);
}