0

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!

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You! It is working now. But I have read that setting of fetchtype in @ManyToOne association don't has any effect on queries. I think I missed something, so I go back to the manuals. :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.