0

I have the following named query

@NamedQuery(name = "UserFlight.getUserFlightDetails", 
query = "SELECT new com.foobar.UserFlightDetails(uf.flight.divertedAirport, uf.flight.number) " +
        "FROM UserFlight uf WHERE uf.user.id=?1 AND uf.flight.id=?2")

The UserFlightDetails constructor is as follows

public UserFlightDetails(Airport airport, String flightNumber) {
    this.setDivertedAirport(airport);
    this.setFlightNumber(flightNumber);
}

divertedAirport is a foreign key in the flight table, path=(uf.flight.divertedAirport)

My problem is when divertedAirport is null (it's a nullable foreign key), my HQL query returns null as the result (The code doesn't even trigger the constructor above), so I don't get the flightNumber which is never null.

If the divertedAirport isn't null, I get both the airport and the flight number fine (and the above constructor gets executed just fine).

What could be causing this and how could I resolve it? I tried some null functions like nullif and coalesce but nothing helped.

I'm using spring boot 1.2.7, hibernate-core 4.3.11.Final

1 Answer 1

0

Probably, the problem is the uf.flight.divertedAirport. This expression do a JOIN between flight and divertedAirport but, as you say, divertedAirport is a fk and can be null.

So, you need to use the LEFT JOIN.

I would rewrite your query like this:

@NamedQuery(name = "UserFlight.getUserFlightDetails", 
query = 
"SELECT new com.foobar.UserFlightDetails(divertedAirport, flight.number) 
FROM UserFlight uf 
JOIN uf.flight flight
LEFT JOIN flight.divertedAirport divertedAirport
JOIN uf.user user
WHERE user.id = ?1 AND flight.id = ?2 ")

I remove the references like uf.user.id for a explicit JOIN (JOIN uf.user user plus user.id), because is more legible and this kind of problem that generated your question is more easy to find using this way to write JPQL queries.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.