简体   繁体   中英

JPA EclipseLink Adding/Updating entities

I'm a bit confused with the way JPA handle adding/updating entities.

ATM, i have this piece of code:

AltContact c = new AltContact("test");
save(c)
System.out.println("ENTITY: " + contains(c));
c.setEnterpriseName("test2");
save(c);
System.out.println("ENTITY: " + contains(c));

The save method is a simple method on the server side of my application requesting a merge on the EntityManager:

public void save (Object e) {
    em.merge(e);
    em.flush();
}

Where em is an instance of EntityManager .

contains is once again a method on server side that will ask the entity manager if a given entity exist in the current persistent context.

The code above create two rows in my table, the first one with the value "test" and the other one with the value "test2", which is not what i want.

I want to create a new row with the value "test" and then, right after the creation of the row, update it and set his value to "test2". I printed out the return of contains after both call to save , false was returned the two times.

I guess the problem come from the fact that my entity is not part of the persistent context after the first call to save so when i call save again, the entity manager consider it's a new entity and create a new row.

How can achieve this updating process?

A few things. First why do you need to use merge() are you serializing the instance, and why? If you just edit the object returned from the persistence context, then you don't need to do any merging or saving.

If you need to edit the object as serialized, or detached, then for a new object you need to return the Id of the object from your save, this is what will link the detached object with the managed one. Ideally you would execute a find() to get the object before you edit it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM