全栈之路-杂篇-JPA多对多配置分析
多对多在复杂查询中是不可避免的,如何更加简便的进行多对多的查询,如何使用JPA来简化多对多的配置以及SQL语句的书写,记录一下
一、多对多的配置
1、前提条件
当我们在做CRUD的时候(哈哈都是CRUD body),总会碰到那种多表联合查询,我们总会写很长的查询语句,当然在JAP 中同样会写SQL语句,只不过JPA会自己自动的生成一种原生的SQL语句,在举例说一下这里的应用场景,在做优惠券的接口的时候,需要关联分类表以及活动表,就是查询某一个分类商品中(在活动时间范围内)的可以使用的优惠券的列表,同时需要关联活动表,在活动时间内进行的优惠券的领取与消费
2、model模型创建
这里面需要注意的是多对多的配置,以及一对多的配置,尤其注意一下优惠券是与分类之间是多对多的配置的
(1)优惠券的model(只贴出几个主要字段)
1 public class Coupon extends BaseEntity { 2 3 @Id 4 private Long id; 5 private Long activityId; // 活动id 6 private Date startTime; // 开始使用时间 7 private Date endTime; // 结束使用时间 8 9 @ManyToMany(fetch = FetchType.LAZY, mappedBy = "coupons") 10 private List<Category> categoryList; 11 12 }
(2)分类的model(只是关键字段)
1 public class Category extends BaseEntity { 2 3 @Id 4 private Long id; 5 6 @ManyToMany(fetch = FetchType.LAZY) 7 @JoinTable( 8 name = "coupon_category", 9 inverseJoinColumns = @JoinColumn(name = "coupon_id"), 10 joinColumns = @JoinColumn(name = "category_id")) 11 private List<Coupon> coupons; 12 }
(3)活动model创建(只是关键字段,部分省略...)
1 public class Activity extends BaseEntity { 2 3 @Id 4 private Long id; 5 6 @OneToMany(fetch = FetchType.LAZY) 7 @JoinColumn(name = "activityId") 8 private List<Coupon> couponList;
二、查询SQL分析
1、查询SQL的编写
这里主要是用JPA来编写SQL的,类似之前的hibernate HQL语句,简化一下我们书写SQL语句的麻烦,例如我们在这里的书写的结构是:
1 select c from Coupon c 2 join c.categoryList ca 3 join Activity a on a.id = c.activityId 4 where ca.id = :cid 5 and c.startTime < :now 6 and c.endTime > :now
这种是可以实现的,其实JPA帮我们封装了一下SQL,其实真实的SQL其实是这种的:
1 select 2 coupon0_.id as id1_4_, 3 coupon0_.create_time as create_t2_4_, 4 coupon0_.delete_time as delete_t3_4_, 5 coupon0_.update_time as update_t4_4_, 6 coupon0_.activity_id as activity5_4_, 7 coupon0_.description as descript6_4_, 8 coupon0_.end_time as end_time7_4_, 9 coupon0_.full_money as full_mon8_4_, 10 coupon0_.minus as minus9_4_, 11 coupon0_.rate as rate10_4_, 12 coupon0_.remark as remark11_4_, 13 coupon0_.start_time as start_t12_4_, 14 coupon0_.title as title13_4_, 15 coupon0_.type as type14_4_, 16 coupon0_.whole_store as whole_s15_4_ 17 from 18 coupon coupon0_ 19 inner join 20 coupon_category categoryli1_ 21 on coupon0_.id=categoryli1_.coupon_id 22 inner join 23 category category2_ 24 on categoryli1_.category_id=category2_.id 25 and ( 26 category2_.delete_time is null 27 and category2_.online = 1 28 ) 29 inner join 30 activity activity3_ 31 on ( 32 activity3_.id=coupon0_.activity_id 33 ) 34 where 35 ( 36 coupon0_.delete_time is null 37 ) 38 and category2_.id=? 39 and coupon0_.start_time<? 40 and coupon0_.end_time>?
内容出处:七月老师《从Java后端到全栈》视频课程
七月老师课程链接:https://class.imooc.com/sale/javafullstack