JPQL Left Join - Filter right rows while returning all left rows
I have a two entities that are related like so.
public class User {
@Column(name = "I开发者_运维知识库D")
private Integer id;
@OneToMany(mappedBy = "customerUserId")
private Collection<FlightBooking> flightBookingCollection;
}
public class FlightBooking {
@Column(name = "ID")
private Integer id;
@Column(name = "STATUS")
private Integer status;
@JoinColumn(name = "CUSTOMER_USER_ID", referencedColumnName = "ID")
@ManyToOne
private User customerUserId;
}
I wan't to return all users but only flights that have a status = 1.
So far I have:
SELECT u FROM User u LEFT JOIN u.flightBookingCollection AS fb WHERE fb.status = 1
But that only returns users that have at least one flightBooking with status of 1.
Thanks!
That is fundamentally wrong approach. JPA mappings are about defining data model, not about defining structure of specific query result. This means that User should have all (in the case of eager fetching) elements of flightBookingCollection loaded when returned as a result of query, not just some of them.
If there is need for other kind of results, dedicate object to present result must be created with appropriate constructor and created with SELECT NEW construct. Examples can be found from this question.
精彩评论