我有一个包含两个子实体列表的实体。在调用EntityManager.find()时,它会基于两个列表的乘积返回重复项。
我使用Spring,Jackson和JPA与Hibernate和SQL Server。
当使用具有第一种子实体N个元素和第二种子实体M个元素的父级进行测试时,它总是返回这两个实体的N*M个元素。
例如下面有3个任务和5个评论,而JPA返回15个元素。(任务列表的5个副本和评论列表的3个副本)
来自控制器的输出为:
Comments 15
Tasks 15
以下是其余的代码。
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>