我刚接触Spring Data JPA,并且有两个实体,并且在stackoverflow中有一些示例,但没有运气。
用户---> * TaxPayment
目标是获得与user_id相关的所有纳税:
User.java
公共类用户扩展AbstractAuditingEntity实现Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
.......... }
TaxPayment.jva
公共类TaxPayment实现Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "payment_date", nullable = false)
private LocalDate paymentDate;
@NotNull
@Column(name = "amount", precision=10, scale=2, nullable = false)
private BigDecimal amount;
@Column(name = "reference")
private String reference;
@ManyToOne
private User user;
public Long getId() {
return id;
}..
}
我不想让User.java中的oneTOMany注释和Taxpayment中映射的列为user_id。
规范类如下:
最终课程TaxPaymentSpecification {
private TaxPaymentSpecification(){
}
static Specification<TaxPayment> hasUser(Long userId){
return new Specification<TaxPayment>() {
@Override
public Predicate toPredicate(Root<TaxPayment> arg0, CriteriaQuery<?> arg1,
CriteriaBuilder arg2) {
// TODO Auto-generated method stub
Root<TaxPayment> root = arg0;
Subquery<Long> subqry = arg1.subquery(Long.class);
Root<User> user = subqry.from(User.class);
final Join<User,TaxPayment> taxpays = root.join("user");
subqry.select(taxpays.<Long> get("user_id"));
subqry.where(arg2.equal(user.<Long> get("id"),userId));
return arg2.in(arg0.get("user_id")).value(subqry);
}
};
}
}
任何人都可以根据我的目标审核此规范是否正确。(获取与user_id相关的所有TaxPayment)。
先谢谢了。 Nyamath
答案 0 :(得分:0)
如果您已经知道userId,则不需要使用子查询,这将是TaxPayment表中user_id的值:
@Override
public Predicate toPredicate(Root<TaxPayment> arg0, CriteriaQuery<?> arg1,
CriteriaBuilder arg2) {
return arg2.equal(arg0.get("user_id"), userId);
}