是否可以优化Hibernate生成的SQL与JoinTable的OneToMany关系?

时间:2014-08-12 19:29:24

标签: sql hibernate jpa one-to-many jointable

我正在使用JPA和Hibernate 4作为提供者,我有以下实体:

@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 ..
}

我有以下JPQL:

SELECT c FROM Customer c INNER JOIN c.phones p WHERE p.id = :phone

Hibernate为其生成以下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=?

我希望Hibernate生成如下的SQL(即没有加入表'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=?

我知道我可以将新实体映射到连接表'customers_phones'将它关联到Customer并在查询中使用它,或者我可以使用本机SQL而不是JPQL,但我想知道是否有更好的方法来实现这个(没有改变实体模型,仍然使用JPQL),也许是一些特定于Hibernate的Query Hint?

0 个答案:

没有答案