jta - Best way to handle JPA merge? -


i'm new whole jpa thing have multiple questions best way handle jpa merge , persist.

  1. 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.

  2. 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 ;)

  1. 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 invoke em.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.

  2. i guess depends on cascading settings. if want automatically persist / merge groups whenever user entity changed - it's safe add user's collection (something user#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 invokes g.adduser(this);.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -