I'm new to the whole JPA thing so I have multiple questions about the best way to handle JPA merge and persist.
I have an user object which should be updated (some values like date and name). Do I have to merge the passed object first or is it safer to find the new object?
Currently my code for updating a user looks like this:
public void updateUserName(User user, String name) { // maybe first merge it? user.setName(name); user.setChangeDate(new Date()); em.merge(user); }
How can I be sure that the user has not been manipulated before the update method is called? Is it safer to do something like 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? I watched multiple videos and saw many examples but they all were different and nobody explained what the best practice is.
What is the best approach to add children to relationships? For example my user object has a connection to multiple groups. Should I call the JPA handler for users and just add the new group to the user group list or should I create the group in a so group handler with persist and add it manually to my user object?
Hope somebody here has a clue ;)