I'm using JPA with Hibernate 4 as provider and I have the following entities:
@Entity
public class Customer {
@Id
private String id;
private String name;
@OneToMany(cascade=CascadeType.ALL)
@JoinTable(name="customers_phones",
joinColumns={@JoinColumn(name="id_customer")},
inverseJoinColumns={@JoinColumn(name="id_phone")}
)
private List<Phone> phones;
.. Getters/Setters ..
}
@Entity
public class Phone {
@Id
private String id;
private String number;
.. Getters/Setters ..
}
And I have the following JPQL:
SELECT c FROM Customer c INNER JOIN c.phones p WHERE p.id = :phone
For which Hibernate is generating the following SQL:
select
customer0_.id as id1_0_,
customer0_.name as name2_0_
from
Customer customer0_
inner join
customers_phones phones1_
on customer0_.id=phones1_.id_customer
inner join
Phone phone2_
on phones1_.id_phone=phone2_.id
where
phone2_.id=?
I'd like Hibernate to generate the SQL like follows (i.e. without joinning table 'Phone'):
select
customer0_.id as id1_0_,
customer0_.name as name2_0_
from
Customer customer0_
inner join
customers_phones phones1_
on customer0_.id=phones1_.id_customer
where
phones1_.id_phone=?
I know I could map a new entity to the join table 'customers_phones' associate it to Customer and use it in the query or I could use native SQL instead of JPQL, but I was wondering if there is a better way to achieve this (without changing entity model and still using JPQL), maybe some Hibernate-specific Query Hint?