Nikita
Nikita

Reputation: 4515

Spring Jpa: change FetchType for entity

Suppose I have Foo entity with one field annotated with @ManyToOne(fetch = FetchType.LAZY). Usually this field is not needed, but in some queries we need all elements with all related entities. I don't want to query database one by one to get associated entities (n+1 select issue). Is there any way to specify fetchType? Something like:

@Repository
public interface FooRepository extends CrudRepository <Foo, String> {
  List<Foo> findAll(FetchType fetchType);
}

Upvotes: 0

Views: 428

Answers (1)

Rahul Raj
Rahul Raj

Reputation: 3459

@OneToMany(fetch = FetchType.LAZY)
List<Address> address;

Let's say you have above code. You can avoid n+1 issue if you do address.size()

getAdress().size()

so that hibernate will load all elements at once instead of loading one by one.

Upvotes: 1

Related Questions