https://github.com/cepr0/duplicate-parent-entities
Spring Data JPA - duplicated parent entities in 'join fetch' repository query methods
https://github.com/cepr0/duplicate-parent-entities
duplicates spring-boot spring-data-jpa
Last synced: about 2 months ago
JSON representation
Spring Data JPA - duplicated parent entities in 'join fetch' repository query methods
- Host: GitHub
- URL: https://github.com/cepr0/duplicate-parent-entities
- Owner: Cepr0
- Created: 2018-01-30T22:01:36.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-03-21T21:34:59.000Z (over 8 years ago)
- Last Synced: 2025-03-11T07:19:21.786Z (over 1 year ago)
- Topics: duplicates, spring-boot, spring-data-jpa
- Language: Java
- Homepage:
- Size: 13.7 KB
- Stars: 1
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
## Spring Data JPA - duplicated parent entities in 'join fetch' repository query methods
Repository query methods with 'join fetch' leads to the duplicate parents.
Number of duplicates corresponds to number of nested children.
To workaround this situation we can use 'distinct' in the query.
But this still does not work with projection.
The similar methods with `@EntityGraph` work as expected.
Example:
```java
@Entity
class Parent extends BaseEntity {
private String name;
@OneToMany(mappedBy = "parent")
private List children;
}
@Entity
class Child extends BaseEntity {
private String name;
@ManyToOne(fetch = LAZY)
private Parent parent;
}
interface ParentProjection {
Integer getId();
String getName();
List getChildren();
}
interface ParentRepo extends JpaRepository {
@EntityGraph(attributePaths = "children")
@Override
List findAll(); // work as expected
@Query("select p from Parent p left join fetch p.children")
List findWithQuery(); // has duplicated parents
@Query("select distinct p from Parent p left join fetch p.children")
List findDistinctWithQuery(); // does not have duplicated parents
@EntityGraph(attributePaths = "children")
List findProjectionsBy(); // work as expected
@Query("select distinct p from Parent p left join fetch p.children")
List findDistinctProjectionsWithQuery(); // has duplicated parents
}
```
More tests is .