Daniel
Daniel

Reputation: 906

Hibernate ignores FetchType for Single Inheritance

I have 3 entities inheriting from another entity. I'm using the strategy Single_Table

@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

E.g. Class B,C and D inherite from A

On entity B I'm loading another entity X eagerly. Unfortunately, Hibernate ignores my annotation and creates a select for each entity B to fetch entity X.

@ManyToOne(fetch=FetchType.EAGER)
private Projekt projekt;

My select statement looks as follows: ´select a from A a´

Some more code examples:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "DType", discriminatorType = DiscriminatorType.STRING, length = 3)
public abstract class A {}


@Entity
@DiscriminatorValue(B.PREFIX)
public class B extends A {

   @ManyToOne(fetch=FetchType.EAGER)
   private Projekt projekt;
}

Now I expect Hibernate to query all classes which inherite from A, which it does. Unfortunately it also executes a select statement for each result row to query "projekt", which I want to avoid.

Upvotes: 2

Views: 1161

Answers (2)

axtavt
axtavt

Reputation: 242706

Hibernate doesn't insert joins into SQL queries generated from the HQL/JPQL ones for FetchType.EAGER.

In order to insert join you need to specify left join fetch explicitly, I guess it won't create problems for InheritanceType.SINGLE_TABLE despite the fact that this relationship doesn't exists in other subclasses:

from A a left join fetch a.projekt

Upvotes: 1

gkamal
gkamal

Reputation: 21000

What do you want it to do? If you do "from A" - then it is fetching entities of all the inherited types. It is not possible (or atleast not easy) to create a sql query that fetching B,C,D and then for B fetch X eagerly.What do you want it to do?

To avoid many queries you can set the BatchSize on the association. That will optimize loading of Xs in batches - instead of one query for each B.

If you are only interested in B entities you can write the query as "from B" in which case the association will be eagerly fetched.

Upvotes: 0

Related Questions