1

I am trying to update single record in database using hibernate, so I want to merge updated object. I am having code to update object and return merged hibernate entity object like,

  protected <T> T updateObject(T o) {
        Session s = getSession();
        @SuppressWarnings("unchecked")
        T mergedObject = (T) s.merge(o);
        s.update(mergedObject);
        return mergedObject;
    }

When I am trying to update Multivalued attribute (e.g. List of addresses), If I add new address in list and call update fuction,

After T mergedObject = (T) s.merge(o); , mergedObject containing null value and transaction becomes failed. How can I do it properly?

1 Answer 1

0

If your object is list then you need to iterate over list and merge particular entity separately. Though you cannot use only String. The object must be a hibernate entity. With hibernate entity you can do like this.

    T mergedObject = null;
    if(o instanceof List){
        for(Object obj: o){
              mergedObject = (T) s.merge(obj);
        }
    }else{
        mergedObject = (T) s.merge(o);
    }
Sign up to request clarification or add additional context in comments.

5 Comments

My object contains List as well as String. It is in the form like,public class User{ private long id; private String userName; private List<String> schemas; private Name name; private Boolean active; private String password; private List<Ims> ims; private List<Address> addresses; private List<Email> emails; }
What will I do when object is of type User (java class)?
Have you done mapping of OneToMany for other list that you mentioned like Address, Email.
Yes. I've done mapping like, @OneToMany(mappedBy = "user", orphanRemoval = true) private List<Email> emails;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.