jta - Best way to handle JPA merge? -
i'm new whole jpa thing have multiple questions best way handle jpa merge , persist.
i have user object should updated (some values date , name). have merge passed object first or safer find new object?
currently code updating user looks this:
public void updateusername(user user, string name) { // maybe first merge it? user.setname(name); user.setchangedate(new date()); em.merge(user); }
how can sure user has not been manipulated before update method called? safer this:
public void updateusername(int userid, string name) { user user = em.getreference(user.class, userid); user.setname(name); user.setchangedate(new date()); em.merge(user); }
maybe other solutions? watched multiple videos , saw many examples different , nobody explained best practice is.
what best approach add children relationships? example user object has connection multiple groups. should call jpa handler users , add new group user group list or should create group in group handler persist , add manually user object?
hope here has clue ;)
it depends on want achieve , how information have origin of object you're trying merge.
firstly, if invoke
em.merge(user)
in first line of method or in end doesn't matter. if use jta , cmt, entity updated when method invocation finishes. difference if invokeem.merge(user)
before changing user should use returned instance instead of parameter, either is:public void updateusername(user user, string name) { user manageduser = em.merge(user); manageduser.setchangedate(new date()); // no need of additional em.merge(-) here. // jta automatically commits transaction business method. }
or
public void updateusername(user user, string name) { user.setchangedate(new date()); em.merge(user); // jta automatically commits transaction business method. }
now updating entity.
if want update well-defined fields in entity - use second approach it's safer. can't sure if client of method hasn't modified other fields of entity. therefore,em.merge(-)
update them might not wanted achieve.on other hand - if want accept changes made user , override / add properties
changedate
in example, first approach fine (merge whole entity passed business method.) depends on use-case.i guess depends on cascading settings. if want automatically persist / merge
groups
wheneveruser
entity changed - it's safe add user's collection (somethinguser#addgroup(group g) { groups.add(g)}
. if don't want cascading, can create own methods propagate other side of relationship. might like:user#addgroup(group g)
automatically invokesg.adduser(this);
.
Comments
Post a Comment