4.2.3 搭建商品微服务,剩余代码

本文深入解析了商品微服务的代码实现,包括DTO、参数、Mapper、Service和Controller等核心组件,展示了如何进行商品信息的保存、分页查询及评论管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写在前面:如果您不是从第4章 服务治理与负载均衡传送门跳转过来的,那么此篇文章对您将毫无意义

商品微服务剩余代码

注意

  1. 项目结构和用户微服务相同
  2. 所用工具也和微服务相同
  3. 只粘贴 dto,param,mapper(部分),service和controller包中的代码
dto

UserDto

@Data
public class UserDto {
    private Integer id;
    private String nickname;
    private String avatar;
}

SysProductDto

@Data
public class SysProductDto {
    private Integer id;

    private String name;

    private String coverImage;

    private BigDecimal price;

    public static SysProductDto adapt(SysProduct product){
        SysProductDto dto = new SysProductDto();
        BeanUtils.copyProperties(product,dto);
        return dto;
    }
}

ProductCommentDto

@Data
public class ProductCommentDto {
    private Integer id;

    private Integer productId;

    private Integer authorId;

    private String content;

    private SysProduct product;

    private UserDto author;

    private ProductComment comment;

    private Date beginTime;

    private Date endTime;

    public static ProductCommentDto adapt(ProductComment comment){
        ProductCommentDto dto = new ProductCommentDto();
        BeanUtils.copyProperties(comment,dto);
        return dto;
    }
}
param

ProductParam

@Data
public class ProductParam {
    private Integer id;
    @NotBlank
    @Length(min = 1,max = 50,message = "商品名称在1~50个字之间")
    private String name;

    private String coverImage;
    @NotNull
    @Min(value = 0,message = "商品价格不能设成负数")
    private BigDecimal price;
}

UserController

@Data
public class ProductCommentParam {
    private Integer id;
    private Integer productId;
    private Integer authorId;
    @NotBlank
    @Length(min = 1,max = 255,message = "评论信息在1~255个字之间")
    private String content;
    private Date createTime;
    private Date beginTime;
    private Date endTime;
}
mapper(部分)

SysProductMapper

public interface SysProductMapper {
    int countByProductDto(@Param("dto") SysProductDto dto);
    List<SysProduct> selectProductListByProductDto(@Param("dto")SysProductDto dto, PageQuery pq);
}

SysProductMapper.xml

<select id="countByProductDto" parameterType="map" resultType="int">
    SELECT count(1)
    FROM `sys_product`
    <include refid="productComditions"/>
  </select>

  <select id="selectProductListByProductDto" parameterType="map" resultMap="BaseResultMap">
    SELECT id, name, cover_image, price
    from `sys_product`
    <include refid="productComditions"/>
    ORDER BY id DESC
    LIMIT #{pq.pageNo},#{pq.pageSize}
  </select>

  <sql id="productComditions">
    <where>
      <if test="dto.id != null">
        AND id = #{dto.id}
      </if>
      <if test="dto.name!=null and dto.name != ''">
        AND name LIKE #{dto.name}
      </if>
      <if test="dto.coverImage!=null and dto.coverImage!=''">
        AND cover_image = #{dto.coverImage}
      </if>
      <if test="dto.price!=null">
        AND price = #{dto.price}
      </if>
    </where>
  </sql>

ProductCommentMapper

public interface ProductCommentMapper {
    int countByCommentDto(@Param("dto") ProductCommentDto dto);
    List<ProductComment> selectCommentListByCommentDto(@Param("dto")ProductCommentDto dto,@Param("pq") PageQuery pq);
}

ProductCommentMapper.xml

<select id="countByCommentDto" parameterType="map" resultType="int">
    SELECT COUNT(1)
    FROM `product_comment`
    <include refid="commentConditions"/>
  </select>

  <select id="selectCommentListByCommentDto" parameterType="map" resultMap="BaseResultMap">
    SELECT id, product_id, author_id, content, create_time
    FROM `product_comment`
    <include refid="commentConditions"/>
    ORDER BY id DESC
    LIMIT #{pq.pageNo},#{pq.pageSize}
  </select>

  <sql id="commentConditions">
    <where>
        <if test="dto.id!=null">
          AND id = #{dto.id}
        </if>
        <if test="dto.productId!=null">
          AND product_id = #{dto.productId}
        </if>
        <if test="dto.authorId!=null">
          AND author_id = #{dto.authorId}
        </if>
        <if test="dto.content!=null and dto.content!=''">
          AND content LIKE #{dto.content}
        </if>
        <if test="dto.beginTime!=null">
          AND create_time &gt; #{dto.beginTime}
        </if>
        <if test="dto.endTime!=null">
          AND create_time &lt; #{dto.endTime}
        </if>
    </where>
  </sql>
service

ProductService(interface)

public interface ProductService {
    /**
     * 保存
     */
    void save(ProductParam param);
    /**
     * 分页查询
     * @param param
     * @param pq
     * @return
     */
    PageResult<SysProduct> getPageList(ProductParam param, PageQuery pq);

    SysProduct loadOne(Integer productId);
}

ProductServiceImpl

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private SysProductMapper sysProductMapper;

    @Override
    public void save(ProductParam param) {
        BeanValidator.check(param);
        SysProduct product = SysProduct.builder().name(param.getName())
                .coverImage(param.getCoverImage()).price(param.getPrice()).build();
        sysProductMapper.insert(product);
    }

    @Override
    public PageResult<SysProduct> getPageList(ProductParam param, PageQuery pq) {
        BeanValidator.check(param);
        SysProductDto dto = new SysProductDto();
        if (null != param.getId()){
            dto.setId(param.getId());
        }
        dto.setName("%"+param.getName()+"%");
        if (StringUtils.isNotEmpty(param.getCoverImage())){
            dto.setCoverImage(param.getCoverImage());
        }
        dto.setPrice(param.getPrice());
        //查询个数
        int count = sysProductMapper.countByProductDto(dto);
        if (count > 0){
            return PageResult.<SysProduct>builder().total(count).data(sysProductMapper.selectProductListByProductDto(dto,pq)).build();
        }
        return PageResult.<SysProduct>builder().build();
    }

    @Override
    public SysProduct loadOne(Integer productId) {
        if (null == productId){
            throw new RuntimeException("参数异常");
        }
        return sysProductMapper.selectByPrimaryKey(productId);
    }
}

ProductCommentService(interface)

public interface ProductCommentService {
    void save(ProductCommentParam param);

    /**
     * 分页查询
     * @param param
     * @param pq
     * @return
     */
    PageResult<ProductComment> getPageList(ProductCommentParam param, PageQuery pq);
}

ProductCommentServiceImpl

@Service
public class ProductCommentServiceImpl implements ProductCommentService {

    @Resource
    private ProductCommentMapper productCommentMapper;

    @Override
    public void save(ProductCommentParam param) {
        BeanValidator.check(param);
        ProductComment pc = ProductComment.builder().productId(param.getProductId())
                .authorId(param.getAuthorId()).content(param.getContent())
                .createTime(param.getCreateTime()).build();
        productCommentMapper.insert(pc);
    }

    /**
     * 分页查询
     * @param param
     * @param pq
     * @return
     */
    @Override
    public PageResult<ProductComment> getPageList(ProductCommentParam param, PageQuery pq) {
        BeanValidator.check(param);
        ProductCommentDto dto = new ProductCommentDto();
        if (null!=param.getId()){
            dto.setId(param.getId());
        }
        if (null!=param.getProductId()){
            dto.setProductId(param.getProductId());
        }
        if (null!=param.getAuthorId()){
            dto.setAuthorId(param.getAuthorId());
        }
        if (null!=param.getBeginTime()){
            dto.setBeginTime(param.getBeginTime());
        }
        if (null!=param.getEndTime()){
            dto.setEndTime(param.getEndTime());
        }
        if (StringUtils.isNotEmpty(param.getContent())){
            dto.setContent("%"+param.getContent()+"%");
        }
        //查询个数
        int count = productCommentMapper.countByCommentDto(dto);
        if (count > 0){
            return PageResult.<ProductComment>builder().total(count).data(productCommentMapper.selectCommentListByCommentDto(dto,pq)).build();
        }
        return PageResult.<ProductComment>builder().build();
    }
}

controller

SysProductController

@RestController
@RequestMapping("/product")
public class SysProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/page")
    public JsonData page(ProductParam param, PageQuery pq){
        return JsonData.success(productService.getPageList(param,pq));
    }

    @RequestMapping("/save")
    public JsonData save(ProductParam param){
        productService.save(param);
        return JsonData.success();
    }
}

SysProductController

@RestController
@RequestMapping("/comment")
public class ProductCommentController {

    @Autowired
    private ProductCommentService productCommentService;
    @Autowired
    private ProductService productService;
    @Autowired
    @Qualifier(value = "restTemplate")
    private RestTemplate restTemplate;

    @RequestMapping("/page")
    public JsonData page(ProductCommentParam param, PageQuery pq){
        return JsonData.success(productCommentService.getPageList(param,pq));
    }

    @RequestMapping("/save")
    public JsonData save(ProductCommentParam param){
        productCommentService.save(param);
        return JsonData.success();
    }

    /**
     * 通过指定商品id查询商品信息,评论者信息,评论内容
     */
    @RequestMapping(value = "/{productId}/comments",method = RequestMethod.GET)
    public List<ProductCommentDto> showMore(@PathVariable Integer productId){
        ProductCommentParam param = new ProductCommentParam();
        param.setProductId(productId);
        PageResult<ProductComment> pq = productCommentService.getPageList(param, new PageQuery());
        if (CollectionUtils.isEmpty(pq.getData())){
            return Lists.newArrayList();
        }
        return pq.getData().stream().map((comment) -> {
            ProductCommentDto dto = new ProductCommentDto();
            dto.setComment(comment);
            dto.setProduct(this.productService.loadOne(comment.getProductId()));
            dto.setAuthor(this.loadUser(comment.getAuthorId()));
            return dto;
        }).collect(Collectors.toList());
    }

    protected UserDto loadUser(Integer userId){
        return this.restTemplate.getForEntity("http://USERSERVICE/users/{id}",UserDto.class,userId)
                .getBody();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值