Matin Kh
Matin Kh

Reputation: 5178

Optimize a query in hibernate with Criteria (avoid unnecessary joins)

I have a class A which has another class B inside it. Something like this:

@Table(name = "A")
Class A {
    @OneToOne
    @JoinColumn(name="B_ID")
    B b;
} 

I want to have a query like this:

SELECT * from A where B_ID = 4

But when I use Criteria to achieve my goal, it inner joins the two tables. How can I have a SELECT just as I said.


If it helps, I am having my Criteria like this:

DetachedCriteria crit = DetachedCriteria(A.class, "a");
crit.createAlias("a.b", "b");
crit.add(Restrictions.eq("b.id", 4));
getHibernateTemplate().findByCriteria(crit);

Upvotes: 1

Views: 2081

Answers (2)

zhfkt
zhfkt

Reputation: 2461

From the How to avoid unnecessary selects and joins in HQL and Criteria. It seems that it is a long-standing bug in Hibernate.

https://hibernate.atlassian.net/browse/HHH-3538

https://hibernate.atlassian.net/browse/JPA-19

This problem confuses me a lot either.

Upvotes: 0

StuPointerException
StuPointerException

Reputation: 7267

One to one relationships are eagerly fetched by default in Hibernate - that's why you're getting an inner join. Try this:

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="B_ID")
B b;

Upvotes: 2

Related Questions