【发布时间】:2013-08-27 07:15:37
【问题描述】:
我无法让这个工作,我找不到我的特殊情况的例子。简而言之:我有一个有关系的主要实体。现在我想复制一个子实体并将这个新的子实体链接到主实体。最好我试着举一个简短的例子。我跳过了 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.
谁能帮我解决这个问题?
【问题讨论】:
-
我不是 Java 开发人员,但在阅读帖子后,我浏览并看到 CascadeDetach 分离了所有导航对象。这与您使用的框架有关吗?
-
因为
CascadeType.ALL我认为我已经做了级联分离。
标签: java entity-framework jpa entity jpa-2.0