Skip to content

Rrepository query methods with 'join fetch' produce duplicated parent entities [DATAJPA-1299] #1623

@spring-projects-issues

Description

@spring-projects-issues

Sergei Poznanski opened DATAJPA-1299 and commented

Repository query methods with 'join fetch' leads to the duplicate parents.
Number of duplicates corresponds to the number of nested children.

To work around this situation we can use 'distinct' in the query. But this still does not work with projections.

The similar methods with @EntityGraph work as expected.

Example:

@Entity
class Parent extends BaseEntity {
	private String name;
	@OneToMany(mappedBy = "parent")
	private List<Child> children;
}

@Entity
class Child extends BaseEntity {
	private String name;
	@ManyToOne(fetch = LAZY)
	private Parent parent;
}

interface ParentProjection {
	Integer getId();
	String getName();
	List<Child> getChildren();
}

interface ParentRepo extends JpaRepository<Parent, Integer> {

	@EntityGraph(attributePaths = "children")
	@Override
	List<Parent> findAll(); // works as expected 

	@Query("select p from Parent p left join fetch p.children")
	List<Parent> findWithQuery(); // has duplicated parents
	
	@Query("select distinct p from Parent p left join fetch p.children")
   	List<Parent> findDistinctWithQuery(); // does not have duplicated parents
	
	@EntityGraph(attributePaths = "children")
	List<ParentProjection> findProjectionsBy(); // works as expected
		
	@Query("select distinct p from Parent p left join fetch p.children")
   	List<ParentProjection> findDistinctProjectionsWithQuery(); // has duplicated parents 
}

More tests is here


Affects: 2.0.5 (Kay SR5)

Reference URL: https://github.com/Cepr0/duplicate-parent-entities

1 votes, 4 watchers

Metadata

Metadata

Labels

in: coreIssues in core supportstatus: declinedA suggestion or change that we don't feel we should currently apply

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions