我无法让这个工作,我找不到我的特殊情况的例子。简而言之:我有一个有关系的主要实体。现在我想复制一个子实体并将这个新的子实体链接到主实体。最好我试着举一个简短的例子。我跳过 getter 和 setter 方法以使其更短:
实体条目:
@Entity
public class Entry implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "entry", cascade=CascadeType.ALL)
private List<EntryData> entriesDataList = new LinkedList<>();
@OneToOne(cascade=CascadeType.ALL)
private EntryData entryData;
}
实体入口数据:
@Entity
public class EntryData implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String subject;
@ManyToOne(optional = false)
private Entry entry;
@ManyToMany(mappedBy = "entries", cascade = {CascadeType.ALL} )
private List<EntryTag> tags = new LinkedList<>();
}
实体入口标签:
@Entity
public class EntryTag implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(unique=true)
private String name;
@ManyToMany()
private List<EntryData> entries = new LinkedList<>();
}
现在我想做以下事情:
@Stateless
public class NewEntryData {
@PersistenceContext
private EntityManager em;
public void makeNewEntryData(){
Entry e = em.find(Entry.class, 10);
em.detach(e);
EntryData ed = e.getEntryData();
ed.setSubject("New Subject");
ed.setId(null);
for (Iterator<EntryTag> it = ed.getTags().iterator(); it.hasNext();) {
it.next().addEntryData(ed);
}
em.merge(e);
}
}
我所期望的:
生成一个新实体EntryData
,其内容与存储在 中的旧实体相同Entry.entryData
,但新主题除外。在Entry.entryData
新的链接中EntryData
生成。旧的EntryData
包含在数据库中。
我得到了什么em.merge(e)
:
org.eclipse.persistence.exceptions.ValidationException
Exception Description: The attribute [id] of class [test.EntryData] is mapped to a primary key column in the database. Updates are not allowed.
有人可以帮我解决这个问题吗?