Nilzor
Nilzor

Reputation: 18573

Why does this JPA code not update entity in AppEngine local datastore?

So I have the follow entity with the following code to create and update the object. The resulting data after calling the method is that the field Value has the value of 1 in the Datastore running at my local computer. Why? Isn't the object JPA-managed (or attached as described in this article) and supposed to update itself upon em2.close()?

Entity:

@Entity 
public class MyObj {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long Id;
    public int Value = 0;
}

Code:

public void createAndUpdate() {
    Long id = null;
    // Line below calls Persistence.createEntityManagerFactory("transactions-optional").createEntityManager()
    EntityManager em1 = Database.getEntityManager(); 
    MyObj obj = new MyObj();
    obj.Value = 1;      
    em1.persist(obj);
    em1.close();
    id = obj.Id;

    EntityManager em2 = Database.getEntityManager();
    obj = (MyObj) em2.find(MyObj.class, id);
    obj.Value = 2;
    // NOTE1
    em2.close();        
}

On the line marked NOTE1 I have tried inserting em2.persist(obj) and em2.merge(obj) (even though from what I've read, that should not be neccessary since find() returns an attached object). None of them helped.

I'm using JPA v1.

Upvotes: 2

Views: 550

Answers (1)

DataNucleus
DataNucleus

Reputation: 15577

As the JPA spec says, you cannot directly update fields of Entity objects, yet in your posted code you do just that (so the persistence provider has no way of knowing that something has changed, and so can't flush those changes to the datastore).

DataNucleus JPA does actually allow you to update the field directly if you enhance the class that does it to be "PersistenceAware".

Solution : use setters to update fields

Upvotes: 2

Related Questions