I have entity with two Lists of children entities. When calling EntityManager.find() it returns duplicates based on multiplication of two lists.
I'm using Spring, Jackson and JPA with Hibernate and SQL Server.
When testing with parent that has N elements of first and M of second child entity it always returns N*M elements of both entities.
For example below there are 3 tasks and 5 comments and JPA returns 15 for both lists. (5 copies of task list, and 3 copies of comment list)
Output from controller is:
Comments 15
Tasks 15
And the rest of the code is below.
controller.java
@RequestMapping(method = RequestMethod.GET)
public String listAll(Model model) {
Goal goal = new Goal();
goal = service.getGoalById(25);
System.out.println("Comments " + goal.getComments().size());
System.out.println("Tasks " + goal.getTasks().size());
return "home";
}
service.java
@Transactional
public Goal getGoalById(int goalId) {
Goal goal = em.find(Goal.class, goalId);
return goal;
}
goal.java
@Entity
@Table(name = "goal")
public class Goal {
@Id
@GeneratedValue
private int id;
@JsonManagedReference
@OneToMany(mappedBy = "tasksGoal", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private List<Task> projectTasks = new ArrayList<Task>();
@JsonManagedReference
@OneToMany(mappedBy = "commentsGoal", cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
private List<Comment> goalComments = new ArrayList<Comment>();
...
}
task.java
@Entity
@Table(name="projectTask")
public class Task {
@Id
@GeneratedValue
private int id;
@JsonBackReference
@ManyToOne (fetch = FetchType.LAZY)
@JoinColumn(name = "task_goal_id")
private Goal tasksGoal;
...
}
comment.java
@Entity
@Table (name="goalComment")
public class Comment {
@Id
@GeneratedValue
private int id;
@JsonBackReference
@ManyToOne (fetch = FetchType.LAZY)
@JoinColumn(name = "goal_id")
private Goal commentsGoal;
...
}
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy" />
<property name="hibernate.connection.charSet" value="UTF-8" />
<!-- Hibernate prints SQL -->
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>