首页 > 解决方案 > spring data jpa规范选择相关3个表

问题描述

我有如下实体;

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Card> cards;
}

  @Entity
public class Card {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    private CardType type;

    @ManyToOne
    private Customer customer;

    @OneToMany(mappedBy = "card", cascade = CascadeType.ALL)
    private List<Product> products;
}

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private Integer count;

    @ManyToOne(fetch = FetchType.LAZY)
    private Card card;
}

public enum CardType {
    SPECIAL, STANDART
}

我试图让客户在他们的特殊类型卡中有产品。

示例数据;

顾客

+----+--------+
| id |  name  |
+----+--------+
|  1 | mike   |
|  2 | john   |
|  3 | robert |
|  4 | sam    |
+----+--------+

+----+----------+-------------+
| id |   type   | customer_id |
+----+----------+-------------+
|  1 | SPECIAL  |           1 |
|  2 | SPECIAL  |           2 |
|  3 | SPECIAL  |           3 |
|  4 | STANDART |           4 |
+----+----------+-------------+

产品

+----+----------+---------+
| id |   name   | card_id |
+----+----------+---------+
|  1 | product1 |       1 |
|  2 | product2 |       2 |
|  3 | product3 |       2 |
|  4 | product4 |       4 |
+----+----------+---------+

查询结果应该是名称为“mike”和“john”的客户,因为他们的专用卡中有产品。

我已经尝试了下面的代码,但它不起作用:

 public static Specification<Customer> hasSpecialProduct() {
        return (root, query, cb) -> {
            Join<Customer, Card> customerCardJoin = root.join(Customer_.cards, JoinType.INNER);
            Predicate cardTypeSpecialPredicate = cb.equal(customerCardJoin.get(Card_.type), CardType.SPECIAL);
            Predicate existsProductsPredicate= cb.exists(customerCardJoin.get(Card_.products));
            return cb.and(cardTypeSpecialPredicate, existsProductsPredicate);
        };
    }

我如何使用规范来做到这一点?有人可以帮助我吗?

标签: jpaspring-data-jpaspring-datacriteria-api

解决方案


推荐阅读