简体   繁体   中英

How to avoid unnecessary inner join on a simple query on entity inheritance mapped with JOINED strategy?

I'm using JPA 2 with Hibernate 4.2.0-Final as provider and I have the following entities:

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {

    @Id
    private String id;

    .. Person attributes ..
    .. Getters/Setters ..
}

@Entity
@Table(uniqueConstraints={@UniqueConstraint(name="UniqueCode", columnNames="code")})
public class Customer extends Person {

    @Column(nullable=false)
    private String code;

    .. Other Customer attributes ..
    .. Getters/Setters ..
}

And I have the following JPQL:

SELECT count(distinct c.code) FROM Customer c

For which Hibernate is generating the following SQL:

select
    count(distinct customer0_.code) as col_0_0_ 
from
    Customer customer0_ 
inner join
    Person customer0_1_ 
        on customer0_.id=customer0_1_.id

But I only need to count Customers with distinct code , which happens to be a field that is specific to Customer, so there is no need for the inner join to 'Person'. I'd like Hibernate to generate the SQL like follows (ie without joinning table 'Person'):

select
    count(distinct customer0_.code) as col_0_0_ 
from
    Customer customer0_

Is there a way to tell Hibernate to avoid the unnecessary inner join? Maybe some Hibernate-specific Query Hint?

The JOINED Strategy in JPA uses a separate table for each class in the object hierarchy.

So if you want to load objects for a subclass you also have to load information from the parent class (As the subclass alone does not represent complete picture without the attributes in the parent class). This results in a JOIN when querying for the sub-object.

From the JPA documentation you can see this as being a main disadvantage for The JOINED strategy.

1 ) Aside from certain uses of the table-per-class strategy described below, the joined strategy is often the slowest of the inheritance models. Retrieving any subclass requires one or more database joins, and storing subclasses requires multiple INSERT or UPDATE statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM