java 一对多关系修改,java – EclipseLink以一对多关系生成重复条...
我正在使用EclipseLink 2.4.1和JPA 2.0.在我的示例中,我有以下類定義:
@Entity
public class Shepard {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToMany(mappedBy = "shepard", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List sheeps;
public void addSheep(Sheep sheep) {
if (sheep != null) {
if (sheeps == null) {
sheeps = new ArrayList<>();
}
if (!sheeps.contains(sheep)) {
sheeps.add(sheep);
}
}
}
}
@Entity
public class Sheep {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name="shepard_id")
private Shepard shepard;
public Sheep(Shepard shepard, String name) {
this.shepard = shepard;
this.name = name;
shepard.addSheep(this);
}
}
現(xiàn)在,當(dāng)我編寫Junit測(cè)試并執(zhí)行以下操作時(shí).注意,Sheep構(gòu)造函數(shù)調(diào)用Shepard.addSheep(Sheep)!
EntityManagerFactory emf = Persistence.createEntityManagerFactory("data");
EnttyManager em = emf.createEntityManager();
Shepard shepard = new Shepard();
// I Persist Shepard
em.getTransaction().begin();
em.persist(shepard);
em.getTransaction().commit();
// II Persist Tilda
Sheep tilda = new Sheep(shepard, "Tilda");
em.getTransaction().begin();
em.persist(tilda);
em.getTransaction().commit();
// III Persist Martha via Shepard
Sheep martha = new Sheep(shepard, "Martha");
em.getTransaction().begin();
em.merge(shepard);
em.getTransaction().commit();
然后為Sheep的命名查詢,我得到了“Tilda”的重復(fù)條目!
當(dāng)我編碼時(shí),這不會(huì)發(fā)生
em.persist(martha);
相反,作為最后一個(gè)實(shí)體管理員訪問.
分析調(diào)試輸出,我可以看到在II之后有一個(gè)[id = 1]的Shepard對(duì)象和一個(gè)[id = 1]的Sheep對(duì)象.
在III之前和之后,Shepard擁有兩個(gè)參考綿羊的參考資料,其中Tilda為[id = 1],Martha為[id = null].
在III之后,Shepard持有兩個(gè)羊的參考,其中[id = 2]為Tilda,[id = 3]為Martha.
從EclipseLink調(diào)試輸出中,我可以看到III在Sheep表中發(fā)出了兩個(gè)insert語句.
在數(shù)據(jù)庫中最終有三個(gè)Sheep條目,其中id為上面列出的.
此外,我收到以下錯(cuò)誤:
[EL Warning]: 2013-06-21 09:53:26.631--UnitOfWork(221387686)--Thread(Thread[main,5,main])--Exception [EclipseLink-7251] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The attribute [id] of class [Sheep] is mapped to a primary key column in the database. Updates are not allowed.
這是EclipseLink的錯(cuò)誤嗎?或者我做錯(cuò)了什么,這里?
總結(jié)
以上是生活随笔為你收集整理的java 一对多关系修改,java – EclipseLink以一对多关系生成重复条...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python mongodb_Pytho
- 下一篇: PCB学习笔记——DRC检查