'Spring Data / JPQL / Hibernate not returning all children from query, and returning wrong children on subsequent queries
I'm using Sprint boot 2.5.12 and I have entities and repo like the following:
@Entity
public class Parent{
private long id;
private String name;
private Collection<Child> children
}
@Entity
public class ChildLink{
private long id;
@ManyToOne(optional = false)
@JoinColumn(name = "parent_id", nullable = false)
private Parent parent;
@ManyToOne(optional = false)
@JoinColumn(name = "child_id", nullable = false)
private Child child;
}
@Repository
interface ParentRepository extends CrudRepository<Parent, Long>{
@Query("select distinct p from parent p left join fetch p.child c where c = ?1")
Set<Parent> findByChild(Child child)
}
I have this data in the database
Parent | id | name | | - | - | | 1 | Parent 1| | 2 | Parent 2|
Child_parent | id | parent_id | child id | | - | - | - | | 1 | 1| 1 | | 2 | 1| 2 | | 3 | 2| 1 | | 3 | 2| 3 |
Child | id | Foobar | | - | - | | 1 | "foo" | | 2 | "bar" | | 3 | "baz" |
When I run a query inside a transaction to get the parents by child, if a parent has multiple children and I run a query for each child the entities returned by the EM only ever have one child, and the subsequent queries don't return the correct children.
So using the data above if I queried for findByChild(childFoo) it would return both parents with only 1 item in the Child collection. So ChildBar would not be there for parent 1 and ChildBaz would not be there for parent 2. If in the same transaction I run findByChild(childBar) I get the correct number of parents (just parent 1), but instead of only have childBar, it still has childFoo. I know why the initial query only returns 1 child instead of both children, and I'm guessing that the entity manager caching the entity is the reason even subsequent queries are returning the wrong results, but I'm not sure what the best way to fix this is.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
