Search code examples
javaspringbuildermapper

How can i translate variable type with mapper? (DTO to DAO)


i wanna use builder & mapper for sending and receiving DTO - DAO - DTO.

here is my Dto class, Mapper, DAO, Controller & Service function.

i wanna set String 'voucherType' to Configure 'VoucherType' by select it from ConfigureRepository.

Dto Class

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ItemDto {
  @Getter
  @NoArgsConstructor(access = AccessLevel.PRIVATE)
  public static class CreateReq {
    @NotBlank
    private String name;
    @NotNull
    private String voucherType;

    public Item createReqToEntity() {
    /* additional jobs for create entity? */
    return ItemMapper.INSTANCE.createReqToEntity(this);
  }
}
...

Mapper

@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface ItemMapper {
  ItemMapper INSTANCE = Mappers.getMapper(ItemMapper.class);

  Item createReqToEntity(ItemDto.CreateReq createReq);
  Item updateReqToEntity(ItemDto.UpdateReq updateReq);

  ItemDto.CreateRes entityToCreateRes(Item item);
  ItemDto.UpdateRes entityToUpdateRes(Item item);
}

here is a constructor which will be used by mapper

public class Item {

@Builder
private Voucher(String name, String voucherType) {
  this.name = name;
  this.voucherType = configureRepository.findByConfigName(voucherType); // FK but i cannot import 'configureRepository.. why?'

  this.id = FMSFactory.uuid();
  this.created = new Date();
  this.updated = new Date();
}

Controller

public ItemrDto.CreateRes saveItemInfo(@RequestBody @Valid ItemDto.CreateReq 
createItemReq) throws Exception {
    return ItemService.saveItemInfo(createItemReq);
}

Service

public ItemDto.CreateRes saveItemInfo(ItemDto.CreateReq reqDto) {
    Item newItem = ItemRepository.save(reqDto.createReqToEntity());
    ItemDto.CreateRes result = ItemDto.CreateRes.entityToCreateRes(newItem);
    return result;
}

Build Output

error: cannot find symbol 'this.voucherType = configureRepository.findByConfigName(voucherType)'

i need to change 'String voucherType' in createReq to 'Configure voucherType' in Item class(DAO) but i don't know where & how i can set it with Mapper.

anyone can help me?


Solution

  • i got a good answer for my previous question.

    i can still use 'mapStruct' to do this.

    ItemMapper

    @Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE)
    public interface ItemMapper {
      ItemMapper INSTANCE = Mappers.getMapper(ItemMapper.class);
    
      Item createReqToEntity(ItemDto.CreateReq createReq, Configure A);
      Item updateReqToEntity(ItemDto.UpdateReq updateReq, configure A);
      // just overwrite specific variable like this.
      // Configure A = creqteReq.A; will be replaced to
      // Configure A = A;
    
      ItemDto.CreateRes entityToCreateRes(Item item);
      ItemDto.UpdateRes entityToUpdateRes(Item item);
    }
    

    just overwrite variable which i want to translate type.