弹簧数据JPA规格选择相关3表

时间:2019-04-18 22:10:04

标签: jpa spring-data-jpa spring-data hibernate-criteria criteria-api

我有如下实体;

@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);
        };
    }

如何使用规格说明? 有人可以帮我吗?

0 个答案:

没有答案