天天看點

SpringBoot+MyBatisPlus多表聯查SpringBoot+MyBatisPlus多表聯查一、前言二、資料庫表設計三、代碼實作四、測試接口總結

SpringBoot+MyBatisPlus多表聯查

文章目錄

  • SpringBoot+MyBatisPlus多表聯查
  • 一、前言
  • 二、資料庫表設計
    • 1.表結構
    • 2.資料庫語句:
  • 三、代碼實作
    • 1.實體類
    • 2.Mapper
    • 3.Service
    • 4.ServiceImpl
    • 5.Controller
  • 四、測試接口
  • 總結

一、前言

臨近畢業,基于SpringBoot架構開發一款遊戲周邊商城系統。在搭建買家端背景時,開發購物車接口子產品時,需要用到多表聯查。經過借鑒網上大神文章後,調試接口成功,在此記錄。

二、資料庫表設計

1.表結構

SpringBoot+MyBatisPlus多表聯查SpringBoot+MyBatisPlus多表聯查一、前言二、資料庫表設計三、代碼實作四、測試接口總結

查詢hobby表中的name、main_image字段 和 cart表中的quantity、checked字段。

2.資料庫語句:

SELECT ncart.quantity,ncart.checked,nhobby.name,nhobby.main_image 
FROM neuedu_cart ncart,neuedu_hobby nhobby 
WHERE user_id=? and ncart.product_id=nhobby.id
           

三、代碼實作

1.實體類

因為友善測試沒有建立VO類,直接将所需要hobby表中的name、main_image字段添加到Cart實體類裡

代碼如下(示例):

import...省略
@Data
@TableName("neuedu_cart")
public class Cart extends BaseEntity{
    private Long id;
    private Integer userId;
    private Integer productId;
    private Integer quantity;
    private Integer checked;
    private String  name;
    private String  mainImage;
}
           

2.Mapper

考慮到前台調取會員id方法較為友善,是以where user_id=? 改為user_id=#{id}。

這裡需要自己寫SQL語句,為了友善,高效是以采用注解版進行多表聯查。

某位大佬說的:①少一個設定,少一個錯誤爆發點 ② 代碼清晰優雅

import...省略
@Mapper
public interface CartMapper extends BaseMapper<Cart> {
@Select("SELECT ncart.quantity,ncart.checked,nhobby.name,nhobby.main_image 
FROM neuedu_cart ncart,neuedu_hobby nhobby 
WHERE user_id=#{id} and ncart.product_id=nhobby.id")
    List<Cart> getCart( Integer id);
}
           

3.Service

import...省略
public interface CartService extends IService<Cart> {
    List<Cart> getCart(Integer id);
}
           

4.ServiceImpl

import...省略
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private CartMapper cartMapper;

    @Override
    public List<Cart> getCart(Integer id) {
        System.out.println(cartMapper.getCart(id));
        return cartMapper.getCart(id);
    }
}
           

5.Controller

import...省略
@RestController
@Slf4j
@RequestMapping("cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @PostMapping("/getCart")
    @ResponseBody
    public Result getCart(Integer id){
        return Result.success(cartService.getCart(id));
    }
           

四、測試接口

SpringBoot+MyBatisPlus多表聯查SpringBoot+MyBatisPlus多表聯查一、前言二、資料庫表設計三、代碼實作四、測試接口總結

圖中所選字段因為沒有查,是以傳回null,是以推薦建立VO類,隻設定所需字段,這樣看起來就會變得比較優雅~

總結

提示:這裡對文章進行總結:

以上就是今天即興所做的一篇筆記,簡單記錄了MybatisPlus的注解版實作多表聯查。

與在賣家端開發過程中采用SSM架構相比較,我想說真香~

參考資料:MybatisPlus官方文檔