Reputation: 728
I am not able to get this working and I find no example for my special case. In short words: I have a main entity with relationships. Now I want to make a copy of a sub-entity and link this new sub-entity to the main entity. Best I try to make a short example. I skip the getter and setter methods to make it shorter:
Entity Entry:
@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 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 EntryTag:
@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<>();
}
Now I want to do the following:
@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);
}
}
What I expected:
A new Entity EntryData
is generated which has the same content as the old one which was stored in Entry.entryData
, except the new subject. In Entry.entryData
a link to the new EntryData
is generated. The old EntryData
consists in the database as it was.
What I get at 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.
Can someone help me how to solve this?
Upvotes: 1
Views: 132
Reputation: 7678
Your column id
of test.EntryData
class is mapped as primary key, so updates are not allowed in id column
I think you are inserting duplicate value in id column
Upvotes: 1