1

I am using Spring Data + Hibernate and have an entity with several @ManyToOne fields. Every field is retrieved by hibernate with separate select query.

I've already tried @Fetch(value = FetchMode.JOIN), but no use,

Example:

 @Entity
 public class MyEntity{
    @Id
    private Long id;

    @JoinColumn(name = "A")
    @Fetch(value = FetchMode.JOIN)
    @ManyToOne
    private A a;

    @ManyToOne
    @Fetch(value = FetchMode.JOIN)
    @JoinColumn(name = "B")
    private B b;
}

Hibernate will perform 3 db trips for MyEntity, A and B.

Is there a way to retrieve my entity and all of its fields with single select where A and B will be joined.?

Edit:

Entities A and B defined like this:

@Entity
public class A{
    @Id
    Long id;
    String name;
}

Repository looks like this (Spring Data creates implementation):

public interface MyEntityRepository extends CrudRepository<MyEntity , Long> {}

And code that loads entity is pretty simple too:

myEntityRepository.findAll();

Edit 2:

I've just written QueryDSL query and for it only 1 select was executed. I'm happy with that at least.

Monty Joe
  • 33
  • 4
  • "FetchMode.JOIN" should get in single select. How are A, B entities defined? – kosa Nov 05 '13 at 17:24
  • 1
    Can you post the code you are using to load the entity? – Alan Hay Nov 05 '13 at 17:33
  • Interesting. Specifying the fetch mode should not even be required. Default for @ManyToOne is Eager and the default FetchMode for Eager is joined. As an experiment can you try marking the @ManyToOne(optional = false) – Alan Hay Nov 05 '13 at 20:03
  • Added @ManyToOne(optional = false), result still the same. I can still see select requests without any joins for each entity. In each FROM clause exactly one table. – Monty Joe Nov 05 '13 at 20:35
  • Well everything seems in order so I can't offer any anything else. If Join was absolutely necessary then it would be possible I guess to override the findOne() and findAll() methods either by annotating the interface methods with @Query("") and specifying fetch join IN JPQL or by providing a Concrete implementation of the repository and using the criteria API. Similar problem is here with an answer up-voted 12 times, although seems no different to what you have done:http://stackoverflow.com/questions/2931936/hibernate-noob-fetch-join-problem. What happens if you do a findOne()? – Alan Hay Nov 05 '13 at 23:16
  • @AlanHay, thanks for response. If I do a findOne() actually everything is retrieved in one select. After browsing link you provided I assume that it might be the issue with Spring Data retrieving collection? – Monty Joe Nov 06 '13 at 08:43
  • Spring Data just delegates to Hibernate Session so probably just one of Hibernate's idiosyncrasies. – Alan Hay Nov 06 '13 at 10:38

0 Answers0