1.表结构
-
base_c1
-
base_c2 含c1ID
-
base_c3 含c2ID
-
base_attr_info 有一个level字段重要,(1 2 3 )对应的是一二三级分类的平台属性名
细节:base_attr_info 数据库里面是没有 attr_value 相关信息的,但是我们定义实体类的时候加上了LIst<attr_value> 集合,目的是便于数据的展示,避免了重复查询
// 平台属性值集合 @TableField(exist = false) private List<BaseAttrValue> attrValueList;
-
base_attr_value 含attr_Id
功能
1. 查询1,2,3,级分类列表
2. 查询平台属性列表 (根据1,2,3,级分类ID)
这个功能稍微优点复杂,因为需要我们自己写xml文件,自定义sql
//当有多个参数的时候,我们必须使用@Param注解
List<BaseAttrInfo> selectBaseAttrInfoList(@Param("category1Id")Long category1Id, @Param("category2Id")Long category2Id, @Param("category3Id")Long category3Id);
<!--
namespace 定义接口的全路径
<select id='mapper文件名' resultMap='名字'></select>
<resultMap id='随便起一个名字' type='这个要写我们实际要接收的数据了' autoMapping='true' (这个就是实体类成员和表字段自动映射) >
<id column='表字段' property='实体类成员变量' (一般我们只写一个id映射就可以了,其余的会自动形成映射)></id>
<collection property='这个其实就是表里面不存在但是实体类里面我们为了业务需求自定义的字段' type='包路径'>
<id column='' property='' autoMapping='true'></id> --> 这个也一样,只需要映射主键即可,其余的会自动映射
</collection>
</resultMap>
-->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper SYSTEM "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!--namespace 定义接口的全路径-->
<mapper namespace="com.atguigu.gmall.product.mapper.BaseAttrInfoMapper">
<!--
resultMap:表示返回的映射结果集
id : 表示唯一标识
type:表示返回结果集的数据类型
autoMapping : 自动映射
-->
<resultMap id="baseAttrInfoMap" type="com.atguigu.gmall.model.product.BaseAttrInfo" autoMapping="true">
<!--id:表示主键 property:表示实体类的属性名 column:表示通过sql 执行以后查询出来的字段名-->
<id property="id" column="id"></id>
<!--result : 表示映射普通字段-->
<!--<result property="" column=""></result>-->
<!--mybatis 如何配置一对多-->
<!--ofType : 返回的数据类型-->
<collection property="attrValueList" ofType="com.atguigu.gmall.model.product.BaseAttrValue" autoMapping="true">
<!--如果有字段重复则起别名-->
<id property="id" column="attr_value_id"></id>
</collection>
</resultMap>
<!--id:表示方法名-->
<select id="selectBaseAttrInfoList" resultMap="baseAttrInfoMap">
SELECT
bai.id,
bai.attr_name,
bai.category_id,
bai.category_level,
bav.id attr_value_id,
bav.value_name,
bav.attr_id
FROM
base_attr_info bai
INNER JOIN base_attr_value bav ON bai.id = bav.attr_id
<where>
<if test="category1Id != null and category1Id != 0">
or (bai.category_id = #{category1Id} and bai.category_level = 1)
</if>
<if test="category2Id != null and category2Id != 0">
or (bai.category_id = #{category2Id} and bai.category_level = 2)
</if>
<if test="category3Id != null and category3Id != 0">
or (bai.category_id = #{category3Id} and bai.category_level = 3)
</if>
</where>
order by bai.category_level, bai.id
</select>
</mapper>
3. 属性的添加、修改
前端穿过来的直接就是一个 base_attr_info ,里面也包含了List<attr_value> ,我们需要写一个接口来完成两个功能(添加,修改), 首先我们可以根据base_attr_info 看是否可以获取到id,如果true则说明是修改,否侧为新增; 操作的策略是先完成对 attr_info 的操作,然后在操作 attr_value; 因为对于attr_value到底是修改还是新增不好判断,所以干脆直接先全部删除attr_value,在新增(设置attr_info_id);
细节:因为设置操作两张表,为了保证事务,所以在方法上添加@Transactional
4. 回显平台属性
根据attr_info_id 先查找atr_info,然后在去找attr_value集合即可
版权声明:本文为C_x_330原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。