开发者

Google App Engine / JPA - a managed entity A of a new entity B is inserted again in datastore

开发者 https://www.devze.com 2023-04-01 22:15 出处:网络
I\'m having an issue with my project. Indeed I\'ve got: @En开发者_如何学运维tity public class Cast {

I'm having an issue with my project. Indeed I've got:

@En开发者_如何学运维tity
public class Cast {
    //[...]
    @ManyToOne(cascade = {CascadeType.PERSIST})
    private Event relatedEvent;
    //[...]
}

and

@Entity
public class Event {
    //[...]
}

Whenever I try to persist a new instance of Cast whose Event member is already managed and persisted, a new Event entry is created anyway (so I end up with new events all the time).

A custom PropertyEditor (Spring) allows to fetch an event given a string value. Then, the cast is persisted by these few calls (nothing fancy there):

EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.persist(cast);
entityManager.close();

entityManagerFactory is a singleton managed by the Spring container.

Any thoughts about why events are persisted again when linked to a new cast ?

Thanks in advance for your help!

Rolf

P.S.: I have run the debugger and did not really find any information.


UPDATE 09/09

I could find more details about the bug. Here is the code that retrieves an Event instance from the datastore:

public Event findById(long id) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    Key key = KeyFactory.createKey(Event.class.getSimpleName(), id);
    Event result = entityManager.find(Event.class, key);
    entityManager.close();
    return result;
}

The IDs are declared this way (in both Cast and Event):

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Key id;

When only 1 event is stored, the entityManager.find actually returns the event. However, as described previously, the cast is persisted together with a new event.

When I try to create a cast again after a first cast-with-event creation, entityManager.find returns null, although the key is valid and exists in the datastore.

I've got a really similar code for Cast retrieval, and I run into no issue.

This is as far as I could go. I still have no idea why this happens.

0

精彩评论

暂无评论...
验证码 换一张
取 消