Search code examples
hibernatejpaconstructorleft-joinjpql

JPA select new constructor cause additional selects


I have a complex JPA/Hibernate problem. I have two entities A and B. A references B, but this relationship is not required.

public class A {

@JoinColumn(name = "b_id", referencedColumnName = "b_id")
@OneToOne
private B b;

}

I write SELECT NEW dto(a.b) FROM A a this generates inner join, which isn't good for me, because a.b can be null and I want all of the A entites. So I rewrite my query like this: SELECT NEW dto(b) FROM A a LEFT JOIN B b We have to use alias (b) to prevent inner join and get only the outer join. Ok I get all line, but I get extra queries, Hibernate generates SELECT queries for all of B entities. Why, how can I stop this, I use left join, because I want only one query.

Edit:

The same problem with inner joins. If use SELECT NEW dto(a.b) FROM A a additional SELECT b FROM B b WHERE b.id = ? occures, but if I call SELECT NEW dto(a.b.id) FROM A a there isn't additional select for B entites.

Edit2:

This is exactly same as my problem: Same problem, without possible solution.

Because I don't load the parent object itself, Hibernate doesn't load eagerly B...


Solution

  • Now I know what was caused the problem, and I also know the solution.

    The partially solution is to use hibernate's setResultTransformer method. Unfortunatelly JPA doesn't support it...