2

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.

1
  • 3
    Your entity will automatically get saved in Database if you are calling the "setter" method from within a method that has "Transactional" annotation. Usually we do it on Service layer. Commented Aug 10, 2017 at 8:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I call the setter method within a test code which is not Transactional.
how are you fetching the entity during your test?

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.