jpa - 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);
};
}
我如何使用规范来做到这一点?有人可以帮助我吗?
解决方案
推荐阅读
- sprite - x位置如何在精灵中工作
- php - 在php中自动命名文件
- rust - 如何将 SystemTime::now() 转换为整数类型?
- ios - ASWebAuthenticationSession 无法修改警告对话框
- postgresql - 构建具有多租户的 Nest.js 应用程序(使用每个租户的 postgres 架构和后续 ORM)并动态切换架构?
- wordpress - 如何将自动换行属性添加到 SyntaxHighlighter Evolved v.3x
- ios - 比较 3 个值并打印最终结果
- php - AJAX:带有文本输入字段数据的图像上传
- python - python中带有循环的总和
- python - 算法:试图从数组中获取索引 |A[i] - i| <=c in log(N) 使用分治算法