Home > Net >  The spring data JPA repository.save method automatically saves all entities?
The spring data JPA repository.save method automatically saves all entities?

Time:09-16

In the following code, why is user1 saved to the database? repository.save method automatically saves all entities?

@RestController
@RequestMapping("/test")
public class Test {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/test")
    public void test() {
        User user1 = userRepository.findById(1);
        user1.setPhone("1");

        User user2 = userRepository.findById(2);
        userRepository.save(user2);
    }
}

CodePudding user response:

The repository doesn't save the entities; instead, JPA is a "magic" system where changes to persistent entities are automatically saved when the transaction commits. Repositories using other persistence technologies do require explicit save operations for each object.

CodePudding user response:

Basically, it depends upon your transaction boundary, if you have an active non-readonly transaction and you are doing some modifications to managed (attached) entities, all the changes will be saved/persisted once transaction is committed. This is fundamental principle of JPA/Hibernate. Ideally attached entities should not be modified if changes are not required.

  • Related