Issue
Two entities with corresponding dtos are given
entities:
class GalleryBlock(
var images: List<Image?>,
override val sortIndex: Int = 0,
) : ArticleBlock(sortIndex)
class Image(
var url: String,
var imageSize: ImageSize,
override var id: Long,
override var lastModified: Date,
override var lastModifiedBy: String? = null ) : DBEntity
enum class ImageSize {
SMALL,
MEDIUM,
LARGE, }
dtos
data class GalleryBlockDto(
var images: List<ImageDto>,
override val sortIndex: Int,
) : ArticleBlockDto
data class ImageDto(
var id: Long,
var url: String,
var imageSize: ImageSize,
)
for the mapping I have written an interface Mapper
interface Mapper<E, D> {
fun fromEntity(entity: E): D
}
for the mapping from class Image to ImageDto I have create a class ImageMapper
@Component
class ImageMapper: Mapper<Image, ImageDto> {
override fun fromEntity(entity: Image): ImageDto {
return ImageDto(entity.id, entity.url, entity.imageSize)
}
}
when mapping the GalleryBlock I did the same but I get a type mismatch.
@Component
class GalleryBlockMapper: Mapper<GalleryBlock, GalleryBlockDto> {
override fun fromEntity(entity: GalleryBlock): GalleryBlockDto {
val images = entity.images
val sortIndex = entity.sortIndex
return GalleryBlockDto(images, sortIndex)
}
}
is my approach correct? and how do I get the type mismatch fixed without changing the fields of Dto and entities?
Solution
In your GalleryBlockMapper you pass Image instances to the GalleryBlockDto. But ImageDto instances are needed. The ImageMapper needs to be injected into the GalleryBlockMapper, so the images can be mapped.
@Component
class GalleryBlockMapper(private val imageMapper: ImageMapper): Mapper<GalleryBlock, GalleryBlockDto> {
override fun fromEntity(entity: GalleryBlock): GalleryBlockDto {
val images = entity.images.map { imageMapper.fromEntity(it) }
val sortIndex = entity.sortIndex
return GalleryBlockDto(images, sortIndex)
}
}
Answered By - user2999226
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.