我有两个实体。
体育:
@Entity
public class Sports implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "SPORT_NAME")
private String name;
...
}
和运动设施:
@Entity
public class SportFacility implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "SPORTFAC_NAME")
private String name;
@OneToMany
private List<Sports> sports;
....
}
然后,我在“运动”表中创建了一些运动,例如:
--id-----name-----
- 0 - Football -
- 1 - Basketball-
- 2 - Golf -
------------------
我需要创建一些运动设施,让我们参加所有运动
List<Sports> listSports = sb.getAllSports(); //JPQL: SELECT s FROM Sports s
SportFacility sportFacility = new SportFacility("Stadium", listSports);
em.getTransaction().begin();
em.persist(sportFacility);
em.getTransaction().commit();
错误:
java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: database.entities.sports[ id=0 ].
我不想使用Cascade.ALL或PERSIST,因为表中只有很少的运动项目,而我始终不需要用相同的运动项目来创建新记录...
谢谢。
最佳答案
例外与以下事实有关:当您尝试持久保存SportFacility时,您检索到的Sports集合不再处于持久性上下文中-持久性上下文默认情况下具有事务作用域(在事务开始时创建,在事务结束时销毁)和EL不知道该如何处理不受控制的对象。
移动
em.getTransaction().begin();
到开始。
关于java - JPA(EclipseLink)无需Cascade.PERSIST即可保持一对多关系。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13714178/