我有一个关于亲子关系的应用程序。每个父母都有一组孩子(一对多),每个孩子都有一个父母(多对一)。在应用程序中,我有一个服务层,在那里我几乎做了以下事情:
public void addChild() {
parent = getParentFromDB();
Child child = new Child();
child.setParent(parent);
saveChild(child);
Set<Child> children = new HashSet<Child>();
children.addAll(parent.getChildren());
children.add(child);
parent.setChildren(children); // notice this line here.
saveParent(parent);
doStuff(parent);
}
服务层是从外观调用的,外观是一个使用@Transactional 注释的常规 Spring bean。当我尝试调用该addChild()
方法时,我得到以下结果:
2013-03-05 17:09:50,195 [qtp511931089-83] WARN org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1062, SQLState: 23000
2013-03-05 17:09:50,196 [qtp511931089-83] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry '25-9' for key 'PRIMARY'
2013-03-05 17:09:50,198 [qtp511931089-83] ERROR org.hibernate.engine.jdbc.batch.internal.BatchingBatch - HHH000315: Exception executing batch [Duplicate entry '25-9' for key 'PRIMARY']
2013-03-05 17:09:50.204:WARN:oejs.ServletHandler:/child/add
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Duplicate entry '25-9' for key 'PRIMARY'
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1306)
我确实在休眠状态下打开了 SQL 日志,似乎休眠状态调用了两次保存!!!如果我删除“//在此处注意此行”行,则一切正常-实体保存在数据库中,我可以在数据库中看到 25-9 关系。问题是在方法的最后我有 doStuff(parent); 与父母及其孩子做一些事情的方法,所以我不能删除“//在这里注意这一行”行
编辑: 这是在孩子中声明父母的方式:
@ManyToOne(fetch = FetchType.EAGER, targetEntity = ParentModel.class, cascade = { CascadeType.REMOVE })
@JoinTable(name = "PARENT_CHILDREN", joinColumns = @JoinColumn(name = "CHILD_ID"), inverseJoinColumns = @JoinColumn(name = "PARENT_ID"))
private ParentModel parent;
这是在父级中声明子级的方式:
@OneToMany(fetch = FetchType.LAZY, targetEntity = ChildModel.class, cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE })
@JoinTable(name = "PARENT_CHILDREN", joinColumns = @JoinColumn(name = "PARENT_ID"), inverseJoinColumns = @JoinColumn(name = "CHILD_ID"))
private Set<ChildModel> children;