8.查询商品详情
1.前言
数据库和实体类在上一节中已经创建,如果有需要,可以查看上一节
2.mapper层
2.1 Productmapper接口
/** * 根据商品id查询商品详情 * @param id 商品id * @return */ Product findById(Integer id);
2.2 ProductMapper.xml
<select id="findById" resultMap="ProductEntityMap"> select * from store.t_product where id = #{id} </select>
2.3 ProductMapper测试
@Test public void findById(){ Integer id = 1; Product product = productMapper.findById(id); System.out.println(product); }
2.3 测试结果
3.service层
3.1 IProductService接口
/** * 根据商品id获取商品详情 * @param id * @return */ Product getById(Integer id);
3.2 IProductService实现类
@Override public Product getById(Integer id) { Product product = productMapper.findById(id); if (product == null){ throw new ProductNotFoundException("商品未找到!"); } product.setCreatedUser(null); product.setCreatedTime(null); product.setModifiedUser(null); product.setModifiedTime(null); return product; }
3.3 ProductServiceImpl测试
@Test public void getById(){ try { Integer id = 2; Product product = productService.getById(id); System.out.println(product); } catch (ServiceException e) { System.out.println(e.getClass().getSimpleName()); System.out.println(e.getMessage()); } }
3.4 测试结果
4.controller层
3.1 BaseController
else if (e instanceof ProductNotFoundException) { result.setState(406); result.setMessage("商品找不到!");
3.2 ProductController
@GetMapping("{id}/details") public JsonResult<Product> getById(@PathVariable("id") Integer id){ Product data = productService.getById(id); return new JsonResult<Product>(OK, data); }
3.3 测试