使用json中的Post创建数据时,我得到一个列表,我想使用dto将其映射到实体类,反之亦然,使用mapStruct
@Mapper(componentModel = "spring", imports = [(java.util.UUID::class)])
interface ListInfoMapper {
@Mappings(
Mapping(target = "name", expression = "java(info.getAppId())"),
Mapping(target = "state", expression = "java(info.isEnabled() == true ? \"enabled\" : \"disabled\")")
)
@Named("toEntityToDto")
fun map(info: ListInfo): AppList
@IterableMapping(qualifiedByName = ["toEntityToDto"])
fun toAppList(infoList: List<ListInfo>): List<AppList>
@Mappings(
Mapping(target = "appList", expression = "java(toAppList(entities))"),
Mapping(target = "nsId", expression = "java(nsId)")
)
fun toDto(nsId: String, entities: List<ListInfo>): ListInfoDto
}
fun ListInfoMapper.convertToListEntity(nsId: UUID, appList: List<AppList>): List<ListInfo> {
val listInfo = mutableListOf<ListInfo>()
appList.forEach { it -> listInfo.add(ListInfo(nsId, it.name, (it.state == "enabled"))) }
return listInfo
}
当我们使用post man发布请求时,URL也将包含ID。 网址是: http://localhost:8080/request/ad3f4tg6-006c-4654-bd13-45f1200a7ee5
my request is:
{
"List":
[{
"name":"some name",
"state":"enabled"
},
{
"name":"any name",
"state":"disabled"
}
]
}
我的答复是:
{
"id": "ad3f4tg6-006c-4654-bd13-45f1200a7ee5",
"appList": [
{
"name": "some name",
"state": "enabled",
"createdOn": "2019-04-05T06:33:54.095+0000"
},
{
"name": "any name",
"state": "disabled",
"createdOn": "2019-04-05T06:33:54.095+0000"
}
]
}
我的Entity类是这样的:
@IdClass(ListInfoIdentity::class)
@Entity(name = "abc_list")
data class ListInfo(
@Id
var id: UUID,
@Id
var listId: String,
var isEnabled: Boolean,
var createdOn: Date = Date()
) {
constructor() : this(UUID.randomUUID(), "", false)
}
data class ListInfoIdentity(
var id: UUID = UUID.randomUUID(),
var listId: String = ""
) : Serializable
在实体中,listId与name相同,isEnabled与state相同。 请提供一些有关如何使用mapstruct进行映射的帮助。
my Input dto is:
@NoArgsKotlin
data class ListInfoInputDto(
@get: NotEmpty var appList: List<AppList>
)
@NoArgsKotlin
data class AppList(
@get: NotBlank var name: String,
@get: NotBlank var state: String,
var createdOn: Date = Date()
) {
constructor(): this("", "", Date())
}
另一个dto:
@NoArgsKotlin
data class ListInfoDto(
var nsId: String,
@get: NotEmpty var appList: List<AppList>
) {
constructor(): this("", mutableListOf(AppList("", "")))
}