What's the correct way to update an entity using Spring Data JPA?

I have an Account table that contains the FK for another table. Option 1:

@Override
@Transactional(readOnly = false)
public Account changePassword(Account existingAccount, String newPassword){
    existingAccount.setPassword(newPassword);
    return accountDAO.save(existingAccount);
}

      

This way, whenever I call save (), a connection is created to retrieve another table ID, THEN the update itself.
Please note that all fields are updated here, even if only the password changes.

EDIT: I figured out that the connection is being made because I am passing the object as a parameter (existingAccount). If I find it in the changePassword method instead, it works fine (no unions). The problem is that I need this entity in the controller for validation, so accessing the same database 2 times is pointless. Option 2:

@Modifying
@Query("UPDATE Account SET password=(:pass) WHERE username=(:username)")
public void changePassword(@Param("username")String username, @Param("pass")String pass);

      

This way, only the custom update in @Query is done.

I think option 2 is probably better when it comes to performance, but option 1 feels more like jpa. Any suggestions are appreciated.

+3


source to share


1 answer


Both of them should be fine. If you want to use the first method, but not update the fields other than the password, you can set up dynamic updates using the annotation @DynamicUpdate(value=true)

:

dynamic-update (optional - defaults to false): Specifies that the UPDATE SQL should be generated at runtime and can only contain columns whose values ​​have changed.



You will need to use the pre-refresh select feature or optimistic locking. select-before-update can be worse than updating all fields.

Apparently this is implementation specific and not part of JPA .

+2


source







All Articles