控制器接收具有空字段的对象

时间:2019-06-21 12:14:07

标签: kotlin

学习Kotlin。

我有DTO。

@JsonInclude(JsonInclude.Include.NON_EMPTY)
open class AbstractDto : Serializable {

    open var id: Long? = null
    open var created: LocalDateTime? = null
    open var updated: LocalDateTime? = null
}

open class UserDto : AbstractDto() {

    open var height: Int? = null
    open var weight: Double? = null
    open var gender: String? = null
    open var birthDate: LocalDateTime? = null
    open val contacts: List<ContactDto> = ArrayList()
}

我有一个控制器,它继承了抽象类,它继承了接口:

@RestController
@RequestMapping("/user")
@ControllerImpl
class UserController : AbstractController<User, UserDto, UserMapper, UserRepository, UserServiceImpl>()

open class AbstractController<
        E : AbstractEntity,
        D : AbstractDto,
        M : AbstractMapper<E, D>,
        R : CommonRepository<E>,
        S : AbstractService<E, D, M, R>
        > : CommonController<D> {

    private val service: S? = null

    override fun save(dto: D?): ResponseEntity<D> = ResponseEntity.ok(service!!.save(dto)!!)

    override fun update(dto: D): ResponseEntity<D> = ResponseEntity.ok(service!!.update(dto)!!)

    override fun get(id: Long): ResponseEntity<D> = ResponseEntity.ok(service!!.get(id)!!)

    override fun getAll(pageable: Pageable): ResponseEntity<Page<D>> = ResponseEntity.ok(service!!.getAll(pageable))

    override fun delete(id: Long): ResponseEntity<Boolean> = ResponseEntity.ok(service!!.delete(id))
}

interface CommonController<D : AbstractDto> {

    @PostMapping
    fun save(dto: D?): ResponseEntity<D>

    @PutMapping
    fun update(dto: D): ResponseEntity<D>

    @GetMapping("/all")
    fun get(id: Long): ResponseEntity<D>

    @GetMapping
    fun getAll(pageable: Pageable): ResponseEntity<Page<D>>

    @DeleteMapping
    fun delete(id: Long): ResponseEntity<Boolean>
}

发送POST请求:

{
    "height": 180,
    "weight": 75,
    "user": 1
}

我的控制器为DTO,所有字段均为空。忠告,怎么了?在转向抽象之前,它在简单的控制器中工作。

1 个答案:

答案 0 :(得分:0)

您应该学习一门Kotlin小型课程,因为您似乎不太了解如何用Kotlin编写OO。

您可以执行以下操作:

open class AbstractDto(open var id: Long? = null,
                       open var created: LocalDateTime? = null,
                       open var updated: LocalDateTime? = null)


open class UserDto(override var id: Long? = null,
                   override var created: LocalDateTime? = null,
                   override var updated: LocalDateTime? = null,
                   var height: Int? = null
                   var weight: Double? = null
                   var gender: String? = null
                   var birthDate: LocalDateTime? = null
                   val contacts: List<String> = ArrayList()) : AbstractDto(id,
        created,
        updated
) 

您可以在不使用构造函数的情况下将字段初始化为null,这样就永远无法更改它们。如果添加构造函数,则应该可以初始化字段。