2

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 (i.e. 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?

Rafael Vanderlei
  • 351
  • 2
  • 10

1 Answers1

0

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.

SpartanElite
  • 624
  • 4
  • 13
  • I know that if I want to load objects for a subclass I would need a JOIN from the parent class, but in my case I just want a COUNT, so there would be no need for the join, would you agree? – Rafael Vanderlei Aug 15 '14 at 13:36
  • Not in your case. Note how you want the count of `DISTINCT` customers. The way JPA does this is based on the the Primary Key '@Id' of your table - which is defined in the `Person` class. – SpartanElite Aug 15 '14 at 15:19
  • Alright.. I tried to simplify the example and it may have confused a little, but the same problem occurs even if I count using an attribute specific to Customer, which in that case would not need anything from the parent superclass, but still Hibernate insists on the inner join to Person. I'm gonna update the question to reflect what I mean. – Rafael Vanderlei Aug 15 '14 at 17:12