When I save the newAddress
using JpaRepository<Address, AddressID>
save method it updates all references of the method scope, including oldRegistration
.
Since I wanna execute other actions with the oldRegistration
data after the newAddress
is saved It is giving me an unexpected behavior.
Registration registerAddress(String cpf, MultipartFile file) throws IOException {
Registration oldRegistration = registrationService.findById(new CPF(cpf)).orElseThrow(RegistrationNotFound::new);
Address oldAddress = addressService.findById(oldRegistration.getAddressId()).orElseThrow(AddressNotFoundException::new);
StorageFile newStorageFile = storageFileService.saveImage(file.getOriginalFilename(), file.getInputStream(), file.getSize());
Address newAddress = oldAddress.setStorageFile(newStorageFile.getId());
Registration newRegistration = oldRegistration.registerAddressFile(newAddress.getId());
addressService.save(newAddress);
Registration savedRegistration = registrationService.save(newRegistration);
storageFileService.findById(oldAddress.getStorageFileId()).ifPresent(storageFile -> {
storageFileService.delete(storageFile);
storageFileService.removeFromStorageAsync(storageFile);
});
return savedRegistration;
}
I'm expecting the oldAddress
keep all its data.
After addressService.save(newAddress);
all data from oldAddress
is setted as the same of the newAddress
.
How to tell Spring does not update every reference that has the same id?
oldAddress
is a managed entity having the same id as newAddress
. You need to EntityManager.detach()
it from the context before saving the newAddress
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.