I have specification:
final String text = "%text%";
final Specifications<PersonEntity> spec = Specifications.where(
(root, query, builder) -> builder.like(builder.lower(root.join(PersonEntity_.addresses, JoinType.LEFT).get(AddressEntity_.addressLine1)), text)
).or(
(root, query, builder) -> builder.like(builder.lower(root.join(PersonEntity_.addresses, JoinType.LEFT).get(AddressEntity_.addressLine2)), text)
).or(
(root, query, builder) -> builder.like(builder.lower(root.join(PersonEntity_.addresses, JoinType.LEFT).get(AddressEntity_.city)), text)
)
After using:
personRepository.findAll(spec);
In logs, I see, that JPA create a query where it joins addresses three times instead of once.
How can I write a Specification where addresses will be joined only once?
I changed it to:
Specifications.where(
(root, query, builder) -> {
final Join<PersonEntity, AddressEntity> addresses = root.join(PersonEntity_.address, JoinType.LEFT);
return builder.or(
builder.like(builder.lower(addresses.get(AddressEntity_.addressLine1)), text),
builder.like(builder.lower(addresses.get(AddressEntity_.addressLine2)), text),
builder.like(builder.lower(addresses.get(AddressEntity_.code)), text),
);
}
);
Now, it is joining only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With