Marco
Marco

Reputation: 13

GAE + JPA + updating entity is losing other entity relation

Hi I´m new using GAE and JPA, and I´m having some problems trying to update an entity. I copy next a code example:

@Entity
public class User {

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

private String userName;

@ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
private Address address;
}

When I save on datastore a User instance it's store without problems. After this, I retrive this instance from the datastore, then I set a new userName and try to update it.

public User updateUser(User user) {
   EntityManager mgr = getEntityManager();
   if (!containsUser(user)) {
      throw new EntityNotFoundException("Object does not exist");
   }
   mgr.persist(user);
}

The update is performed, the new userName is stored in the dataStore, but as the Address field has FetchType.LAZY I'm losing the persisted value on the update. How can I make an update of some fields without losing other values?

Upvotes: 0

Views: 64

Answers (1)

ltiritilli
ltiritilli

Reputation: 26

Try getting and saving the entity in the same method, otherwise you will lost the session and the manager will recognize the lazy attributes as null ones.

Hope it helps!

Upvotes: 1

Related Questions