Home > Software design >  Map List < Object > to List < ObjectSrv >
Map List < Object > to List < ObjectSrv >

Time:04-21

I want to Map List < City > to List < CitySrv > in the service layer but i dont have any idea how to do that.

the City srv that i want to Map: (srv = server response value)

@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
    public class CitySrv {
        private Long id;
        private String name;
        private Long state;
    }

the City Entity that want to map From:

@AllArgsConstructor
@NoArgsConstructor
@Entity
@SuperBuilder
@Getter
@Setter
@Table(name = "IOTP_CITY")
public class City extends BaseEntity {
    @Column(name = "NAME")
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "state_id")
    private State state;

    @OneToMany(mappedBy = "city")
    private List<Branch> branches = new ArrayList<Branch>();

}

i used Model mapper before but for some reason i cant use it anymore.

        @Override
    public GenericResponse<List<CitySrv>> getAllCities() throws ProjectException {
        Optional<List<City>> citiiesSrvResponse = cityRepository.getAllCities();
        if (citiiesSrvResponse.isPresent()) {
            List<CitySrv> citiesList = modelMapper.map(citiiesSrvResponse.get(), new 
                TypeToken<List<CitySrv>>() {
            }.getType());
            return ResponseUtil.getResponse(citiesList);
        } else throw new ProjectException(ExceptionStatus.NOT_FOUND);
    }

CodePudding user response:

i handle it just like this but its not so good

public GenericResponse<List<CitySrv>> getAllCities() throws ProjectException 
    {
    Optional<List<City>> citiiesSrvResponse = cityRepository.getAllCities();
    CitySrv citySrv = new CitySrv();
    List<CitySrv> citySrvList = new ArrayList<>();
    if (citiiesSrvResponse.isPresent()) {
        for (City eachCity : citiiesSrvResponse.get()) {
            citySrv.setId(eachCity.getId());
            citySrv.setName(eachCity.getName());
            citySrv.setState(eachCity.getState().getId());
            citySrvList.add(citySrv);
        }
        return ResponseUtil.getResponse(citySrvList);
    } else throw new ProjectException(ExceptionStatus.NOT_FOUND);
}

CodePudding user response:

For modelMapper to work your source and destination have to be similar enough. You want to map the entity State in City to a Long which is its id in CitySrv. Which I would guess doesn't fulfill this criteria. You have to tell modelMapper how to map that by configuring a mapping

TypeMap<City, CitySrv> propertyMapper = modelMapper.createTypeMap(City.class, CitySrv.class);
propertyMapper.addMappings(
    mapper -> mapper.map(src -> src.getState().getId, CitySrv::setState)
);

Best you do that in a global config. You can find more info in this baeldung article

  • Related