Musaddique S
Musaddique S

Reputation: 1567

spring data jpa findAll() not working properly

I am having below classes

@Entity
@Table(name = "USR_E_GROUPS")
public class GroupEntity {
    @Id
    @Column(name = "UIDUSERGROUP")
    @GenericGenerator(name = "generator", strategy = "uuid2")
    @GeneratedValue(generator = "generator")
    private String id;
  .........
   @OneToMany(mappedBy = "group", cascade = CascadeType.PERSIST)
   private List<UserGroupEntity> users;

same is for UserGroupEntity now if I use groupRepoository.findAll() It's is firing select query for every Group and inside different select query for UserGroupEntity. so it's taking too much time. I want to make it to fire select with join so it will be a single query.

Upvotes: 0

Views: 4228

Answers (1)

This is probably an n + 1 issue.

From the docs

By default, Hibernate3 uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

By default the children are fetched lazily. Use JOIN FETCH to get the result in a single query.

In your GroupRepoository

@Query("SELECT g FROM GroupEntity g JOIN FETCH g.users gu")
List<GroupEntity> findAllEager();

Upvotes: 1

Related Questions