4

I have the following query:

Query query1 = getEntityManager().createQuery(
" select o from Customer o  " +
" where lower(o.person.name) like :name escape '!' " +
" or lower(o.company.name) like :name escape '!'");

And my mapping is:

@Entity
public class Customer extends AbstractBaseEntity {

@OneToOne(optional = true, cascade = CascadeType.ALL)
private Company company;

@OneToOne(optional = true, cascade = CascadeType.ALL)
private Person person;
...
}

The problem is: Each Customer may be a Person OR a Company, but not both at same time. This means that one of these entities will be always null.

With the query that I wrote, it will only fetch the result when both of the entities are not null, which is a behavior that I didn't expect.

Does anyone know how to create a query that searches for Person.name when Company.name is null and search for Company.name when Person.name is null?

I can make 2 separated queries, but I'm trying to do it all just in one query to perform the spring-data-jpa pagination.

1 Answer 1

3

Use an explicit LEFT JOIN for that:

SELECT cu from Customer cu  
LEFT JOIN cu.person p
LEFT JOIN cu.company co
where lower(p.name) like :name escape '!' 
or lower(co.name) like :name escape '!'
Sign up to request clarification or add additional context in comments.

5 Comments

Sure! But if the person is null and i'm looking for a comapny name?
Of course that was only an example to show you the idea :) Answer updated. Please don't tell me now that there is no SELECT part in my example :)
Of course =) Thanks again. Sadly it doesn't works with the OR statement. I execute in separated queries and works normally. This is strange. I've double checked all parameters and syntax...
Another idea is to use an explict LEFT JOIN. If you dont get it, I will post another answer later.
Nice! It works using left join! Thanks! Just edit your answer with the left join to mark as correct =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.