Reputation: 111
tnxRepository is extending JpaRepository, why both entities are getting saved when I am only saving one? CrudRepository only saves the target one.
Tnx tnx = tnxRepository.findById(id);
tnx.txt = txt;
Tnx tnx2 = tnxRepository.findById(2);
tnx2.txt = txt;
tnxRepository.save(tnx);
Upvotes: 1
Views: 2595
Reputation: 379
JpaRepository ties your repositories to JPA persistence technology, hence on save(), both the objects get persisted. Also, JpaRepository extends CrudRepository, so it provides all the functionalities offered by CrudRepository and more.
CrudRepository is a base interface that provides CRUD operations. Hence, not all the objects get persisted,but only the one you saved.
Upvotes: 2
Reputation: 9261
See saveAll method.
eg.
Tnx tnx = tnxRepository.findById(id);
tnx.txt = txt;
Tnx tnx2 = tnxRepository.findById(2);
tnx2.txt = txt;
tnxRepository.saveAll(List.of(tnx, tnx2))
Upvotes: 0
Reputation: 18430
Because for persistent entities hibernate automatically detect change of it and update the database. Even if you don't save last one both entity will updated.
Upvotes: 2