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;
}
ProductServiceImpl
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());
}
}
service測試
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 測試