Saving a referenced existing entity results in a new entity [message #1239745] |
Tue, 04 February 2014 18:46  |
Eclipse User |
|
|
|
Hi all,
I've the following entities:
@Entity()
public class Contact {
@ManyToOne(cascade = { CascadeType.MERGE, CascadeType.REFRESH,
CascadeType.PERSIST })
private Address address = null;
private String fooBar;
}
@Entity()
public class Address {
private Long id = null;
private String street = null;
private String cityAddon = null;
}
@Entity()
public class Document {
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE,
CascadeType.REFRESH, CascadeType.DETACH })
private Contact contact = null;
private String baz;
}
At first I save some Contacts in my DB, which works good. Then I create
some Documents. I will use the existing Contacts for them. Therefore at
first I select the Contacts from DB:
....
Contact selectedContact = em.findById(givenId);
Document newDoc = new Document();
newDoc.setContact(selectedContact);
em.save(newDoc);
....
This results in a newly created Document (which is correct :-) ) *and* a
new Contact (and a new Address, which results from the new Contact)! I
really don't know why. Any ideas?
TIA,
Ralf.
|
|
|
|
Re: Saving a referenced existing entity results in a new entity [message #1244028 is a reply to message #1240438] |
Tue, 11 February 2014 15:25  |
Eclipse User |
|
|
|
Am 06.02.2014 14:09, schrieb Lukas Jungmann:
> Hi,
>
> it looks like a call to em.findById is done out of a transaction and
> therefore returned entity is in detached state. Now when you try to
> store new document, and that should be done within some transaction, EM
> thinks, that Contact is new since it lost track of it. So you should
> wrap your code with sth like
> em.getTransaction().begin();....em.getTransaction().commit(); to get it
> working as expected.
>
> HTH,
> --lukas
Hm. This is a little complicated since I'm using Eclipse Gemini (with
EclipseLink) as persistence layer. Maybe I've to ask this question there.
Regards,
Ralf.
|
|
|
Powered by
FUDForum. Page generated in 0.05720 seconds