Through using MapStruct, you can define fetchUser method as default one to handle with toEntity process
@Mapper(componentModel = "spring",
uses = UserRepository.class)
public interface AddressMapper {
@Mapping(target = "user",
expression = "java(fetchUser(dto.getUserId(), userRepository))")
Address toEntity(CreateAddressDTO dto, @Context UserRepository userRepository);
default User fetchUser(Long id, UserRepository repo) {
return repo.findById(id)
.orElseThrow(() -> new EntityNotFoundException("User not found: " + id));
}
}
Next, you can add these code block shown below to relevant service.
Address address = addressMapper.toEntity(dto, userRepository);
addressRepo.save(address);
I hope you can help you fix your issue.