当我使用newAddress保存方法保存JpaRepository<Address, AddressID>时,它会更新方法范围的所有引用,包括oldRegistration

由于我想在保存oldRegistration之后对newAddress数据执行其他操作,这给了我意外的行为。

    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;
    }


我期望oldAddress保留所有数据。

addressService.save(newAddress);之后,来自oldAddress的所有数据都将设置为与newAddress相同的数据。

如何判断Spring不会更新具有相同ID的每个引用?

最佳答案

oldAddress是具有与newAddress相同的ID的管理实体。保存EntityManager.detach()之前,需要从上下文中newAddress

关于java - 如何强制 hibernate 而不更新具有相同ID的所有实体?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57762779/

10-09 00:22