79683997

Date: 2025-06-29 19:40:55
Score: 1
Natty:
Report link

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.

Reasons:
  • RegEx Blacklisted phrase (3): you can help
  • Long answer (-0.5):
  • Has code block (-0.5):
  • High reputation (-1):
Posted by: Sercan Noyan Germiyanoğlu