SpringBoot+MyBatisPlus多表联查
文章目录
- SpringBoot+MyBatisPlus多表联查
- 一、前言
- 二、数据库表设计
-
- 1.表结构
- 2.数据库语句:
- 三、代码实现
-
- 1.实体类
- 2.Mapper
- 3.Service
- 4.ServiceImpl
- 5.Controller
- 四、测试接口
- 总结
一、前言
临近毕业,基于SpringBoot框架开发一款游戏周边商城系统。在搭建买家端后台时,开发购物车接口模块时,需要用到多表联查。经过借鉴网上大神帖子后,调试接口成功,在此记录。
二、数据库表设计
1.表结构
查询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));
}
四、测试接口
图中所选字段因为没有查,所以返回null,所以推荐新建VO类,只设定所需字段,这样看起来就会变得比较优雅~
总结
提示:这里对文章进行总结:
以上就是今天即兴所做的一篇笔记,简单记录了MybatisPlus的注解版实现多表联查。
与在卖家端开发过程中采用SSM框架相比较,我想说真香~
参考资料:MybatisPlus官方文档