Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA - Specifications join

Tags:

java

spring

jpa

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?

like image 795
ByeBye Avatar asked Sep 05 '16 08:09

ByeBye


1 Answers

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.

like image 104
ByeBye Avatar answered Nov 11 '22 05:11

ByeBye