I'm currently on spring-boot-starter-data-jpa:2.7.0 which uses hibernate:5.6.9.
I've got a strange behavior when chaining multiple entities.
I got three Entities, where E1 contains a OneToMany-List of E2 which also contains a OneToMany-List of E3:
@Entity
public class E1 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false, updatable = false)
UUID id;
@OneToMany(mappedBy = "e1", fetch = FetchType.EAGER)
List<E2> e2;
}
@Entity
public class E2 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false, updatable = false)
UUID id;
@ManyToOne
E1 e1;
@OneToMany(mappedBy = "e2", fetch = FetchType.EAGER)
List<E3> e3;
}
@Entity
public class E3 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id", nullable = false, updatable = false)
UUID id;
@ManyToOne
E2 e2;
}
For each entity I defined simple repositories like:
@Repository
public interface E1Repository extends JpaRepository<E1, UUID> {}
Additionally I got according repository classes to access the date. Storing is fine and works fine.
When storing one E1 with a list of one E2 having a list of two E3 leads to the proper data in my database table.
Retrieving the data using e1Repository.findAll() is fine and returns the expected Entity e1 with one e2 and two e3.
However when retrieving the data using e1Repository.findById(id) it returns one e1 entity with two e2 each containing two e3. The two e2 are both the same with the same ID.
When changing the List<E?> to a Set<E?> it works correctly, but is just a workaround.
Has anyone an explanation for this behavior? What am I doing wrong or what can I change to get my data right?
Many thanks!