Reputation: 7719
In one of the Rest controllers of my spring app, an instance of an entity gets loaded from the db, a field of it is changed through calling setXX
method on that entity and finally it's saved back to the db .
I wonder if it is possible to update this instance in the database automatically after each call to its setXX
methods. I know that performance-wise it is not ideal, but it would work for me in some cases.
Edit 1
This is a test code where I'm saving/loading the entity. I call the following helper method in a util class to save user details to the db:
public CustomUserDetails createUser(String username, String name, String description, String imageId) {
User user = new User();
user.setName(name);
user.setDescription(description);
user.setImageId(imageId);
CustomUserDetails userDetails = new CustomUserDetails(username,
DUMMY_PASSWORD, true, true, true, true,
AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
userDetails.setUser(user);
userDetailsRepository.save(userDetails);
return userDetails;
}
And in the test, I get the User
instance by calling getUser
on the returned value from this method. I setXX
some values, but it's not persisted.
Upvotes: 2
Views: 1710
Reputation: 21381
Following the code excerpt addition
User user = new User();
This is not a Managed entity.. You'll need to persist it and/or retrieve it from DB for your follow-up setter calls to be persisted (assuming Transaction is still on).
As long as the Entity is in the Managed/Persistent state then (as per the documentation)
any changes will be automatically detected and persisted when the persistence context is flushed. There is no need to call a particular method to make your modifications persistent.
Also as it's commented, within a Spring @Transactional
method, fetching an Entity (therefore being in the Managed/Persistent state) followed directly by a setter property call will result in persisting the property.
Upvotes: 4