I'm trying to utilize the ModelMapper
in my convertion process. What I need to do is to convert the Sample
entity to SampleDTO
object.
I have the Sample
entity like the following:
@Entity
@Table(name = "sample", schema = "sample_schema")
@Data
@NoArgsConstructor
public class Sample {
private static final String SEQUENCE = "SAMPLE_SEQUENCE";
@Id
@SequenceGenerator(sequenceName = SEQUENCE, name = SEQUENCE, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
private Long id;
@Column(name = "name")
private String name;
@Column
private String surname;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "id_deetails")
private Details details;
}
Which holds the Details
one:
@Entity
@Table(name = "details", schema = "sample_schema")
@Data
@NoArgsConstructor
public class Details {
private static final String SEQUENCE = "DETAILS_SEQUENCE";
@Id
@SequenceGenerator(sequenceName = SEQUENCE, name = SEQUENCE, allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = SEQUENCE)
private Long id;
@Column(name = "street_name")
private String streetName;
@Column
private String city;
}
I'd like the DTO to be this format:
@NoArgsConstructor
@AllArgsConstructor
@Data
public class SampleDTO {
private Long id;
private String name;
private String surname;
private String streetName;
private String city;
}
I also made a ModelMapper bean like:
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
And I made a converter component:
@Component
public class EntityDtoConverter {
private final ModelMapper modelMapper;
@Autowired
public EntityDtoConverter(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}
public SampleDTO sampleToDto(Sample entity) {
return modelMapper.map(entity, SampleDTO.class);
}
}
The problem is
when I try to use this mapper converter in my service
@Service
public class SampleService {
private final SampleRepository sampleRepository;
private final EntityDtoConverter entityDtoConverter;
@Autowired
public SampleService(SampleRepository sampleRepository, EntityDtoConverter entityDtoConverter) {
this.sampleRepository = sampleRepository;
this.entityDtoConverter = entityDtoConverter;
}
public List<SampleDTO> getSamples() {
List<SampleDTO> samples = sampleRepository.findAll()
.map(entityDtoConverter::sampleToDto);
return new List<SampleDTO>(samplesPage);
}
}
I get nulls in places of Details
fields.
I have followed Baeldung's tutorial about model-to-dto conversion with ModelMapper and the documentation of it as well but the least wasn't much of help. There is something I'm missing and I have no idea what it is.
I'm working on:
- Java 11
- Spring Boot 2.3.0
- ModelMapper 2.3.8