Spring Data JPA Specification API join by @Embedded property

31 views Asked by At

I have the following entities:

@Getter
@Setter
@Entity
@Table(name = "closing_account")
public class ClosingAccount {

  @Embedded private AccountParams accountParams = new AccountParams();
}

@Getter
@Setter
@Embeddable
public class AccountParams {

  @ToString.Exclude
  @EqualsAndHashCode.Exclude
  @Fetch(FetchMode.SELECT)
  @OneToMany(mappedBy = "closingRequestId", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
  @LazyCollection(LazyCollectionOption.FALSE)
  private List<CheckBook> checkBooks;
}

@Getter
@Setter
@Entity
@Table(name = "checkbook")
public class CheckBook {

  @Column(name = "closing_account_id", nullable = false)
  private UUID closingRequestId;
}

And what I want here is to use Spring Data JPA Specification API (it is important) to craete a Specification with the Predicate to filter only those records from closing_account table where there are no corresponding checkBooks entries. Essentially, from the plain SQL perspective, I want something like:

SELECT ca.* FROM closing_account ca 
LEFT JOIN checkbook cb ON cb.closing_account_id = ca.id
WHERE cb.id IS NULL

It may of coruse be written i different ways, but I just want to express what I need.

It would be possible to just issue:

return (root, query, criteriaBuilder) -> {
  return criteriaBuilder.isNull(root.join("checkBooks", JoinType.LEFT).get("closingRequestId"));
};

however, this is not going to work since checkBooks is not a direct property of a ClosingAccount. So I think I just need to adjust my Specification returned Predicate a bit, I just do not know how.

Any suggestions are welcomed and highly appretiated

0

There are 0 answers