spring boot jpa多条件复杂子表查询

@Entity
@Table(name = "cucu_favo")
public class BaseCucuFavo {
    @EmbeddedId
    private BaseCucuFavoKey id;
    @Column(name = "create_time", nullable = false)
    private Timestamp addTime;

    public BaseCucuFavoKey getId() {
        return id;
    }

    public void setId(BaseCucuFavoKey id) {
        this.id = id;
    }

    public Timestamp getAddTime() {
        return addTime;
    }

    public void setAddTime(Timestamp addTime) {
        this.addTime = addTime;
    }
}




@Embeddable
public class BaseCucuFavoKey  implements Serializable {
    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "user_id", nullable = false)
    private BaseCucuUserInfo cucuUserInfo;

    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "mov_id", nullable = false)
    private BaseCucuMov baseCucuMov;

    public BaseCucuUserInfo getCucuUserInfo() {
        return cucuUserInfo;
    }

    public void setCucuUserInfo(BaseCucuUserInfo cucuUserInfo) {
        this.cucuUserInfo = cucuUserInfo;
    }

    public BaseCucuMov getBaseCucuMov() {
        return baseCucuMov;
    }

    public void setBaseCucuMov(BaseCucuMov baseCucuMov) {
        this.baseCucuMov = baseCucuMov;
    }
}

//查询语句
public Page<BaseCucuFavo> findByUserId(Integer userId,Integer pageNo,Integer pageSize){
        Sort sort = Sort.by(Sort.Order.desc("addTime"));
        PageRequest pageable = PageRequest.of(pageNo , pageSize,sort);
        return baseCucuFavoDao.findAll((root, query, cb) -> {
            List<Predicate> list = new ArrayList<>();
            Join<BaseCucuFavoKey, BaseCucuFavo> favoKeyJoin = root.join("id", JoinType.LEFT);
            Join<BaseCucuUserInfo, BaseCucuFavoKey> userInfoJoin = favoKeyJoin.join("cucuUserInfo", JoinType.LEFT);
            list.add(cb.equal(userInfoJoin.get("id"), userId));
            Predicate[] predicates = list.toArray(new Predicate[list.size()]);
            return cb.and(predicates);
            
        },pageable);
    }

你可能感兴趣的:(jpa,springboot)