Skip to content
Advertisement

Spring data JPA: Three entities ManyToMany relations, query duplicate result with findById

User.java

JavaScript

UserRole.java

JavaScript

RolePermission.java

JavaScript

JDK:17 SpringBoot:2.7.4

findById and findBy are also generate different structure SQL. findById uses left outer Join. findByName uses subquery.

the user only have one role, the role have three permissions.

if use findByUsername It will return the user info correctly.

JavaScript

If I use findById, the same role repeat three times。

JavaScript

}

code : https://github.com/shuanshuan/demo-questions

Advertisement

Answer

While fetching data using id Spring Data JPa considers your fetch = FetchType.EAGER but while fetching with other property it ignores and lazy loads those so you don’t see duplicate records.

To achieve same output at both query you need to add how Spring Data JPA construct query.

JavaScript

The @Fetch annotation is from org.hibernate.annotations package.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement