nerd
nerd

Reputation: 869

Hibernate generates multiple SQL queries even when I use Left join fetch

I have an interesting problem with hibernate, the model looks like the following:

@NamedQueries({
    @NamedQuery(name = "A.test", query = "SELECT DISTINCT a FROM A a LEFT JOIN FETCH a.pk.b WHERE a.pk.b.pk.c.id = :cId AND a.pk.b.pk.d.id = :dId")
})
@Entity
@Table(name = "AT")
public class A implements Serializable {

    @EmbeddedId
    private APK pk;
}

@Embeddable
public class APK implements Serializable {

    @ManyToOne
    @JoinColumns({@JoinColumn(name = "***", referencedColumnName = "***"),
                  @JoinColumn(name = "***", referencedColumnName = "***")
    })
    private B b;
}

@Entity
@Table(name = "BT")
public class B implements Serializable {

    @EmbeddedId
    private BPK pk;
}


@Embeddable
public class APK implements Serializable {

    @ManyToOne
    @JoinColumn(name = "***", referencedColumnName = "***")
    private C c;

    @ManyToOne
    @JoinColumn(name = "***", referencedColumnName = "***")
    private D d;
}

The problem is that the named query makes additional SQL queries... What is the problem? Thanks!

Upvotes: 0

Views: 1755

Answers (1)

Steve Lancashire
Steve Lancashire

Reputation: 1183

Hibernate eagerly fetches many to one references by default. When selecting for "A" in your named query there are a number of many to one references that will get resolved and these will correspond to the SQL queries you are seeing. This default behaviour of hibernate can be overridden by judicious placement of lazy loading on your many to one annotations, i.e.:

@ManyToOne(fetch=FetchType.LAZY)

Upvotes: 1

Related Questions