Ktorm实体作为springboot控制器参数

Ktorm entities as springboot controller parameters

我正在尝试在我的新 springboot 应用程序中使用 Ktorm,但在尝试使用 Ktorm 实体接口作为 springboot 控制器参数时遇到了问题。

实体和控制器如下所示:

// Controller definition
@RestController
class TaskController() {

    @PostMapping
    fun addTask(
        @RequestBody task: Task
    ): Long {
        // ... do something with `task`
    }
}

// Entity definition (unncessary properties are omitted)
interface Task : Entity<Task> {

    var id: Long
    var title: String
    var content: String

    companion object : Entity.Factory<Task>()
}

我在调用函数 addTask():

时遇到了这个异常

[HttpMessageConversionException] Type definition error: [simple type, class website.smsqo.entity.Task]; nested exception is:

[com.fasterxml.jackson.databind.exc.InvalidDefinitionException] Cannot construct instance of website.smsqo.entity.Task (no Creators, like default constructor, exist):

abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: (PushbackInputStream); line: 1, column: 1]" }

(参数task由RequestBody从前端传过来)

我想可能是因为springboot作为一个接口,找不到合适的初始化方式Task。但是,重构成这样肯定不是一个优雅的解决方案:

@RestController
class TaskController() {

    @PostMapping
    fun addTask(
        id: Long, title: String, content: String // even more fields...
    ): Long {
        val task = Task {
            this.id = id
            this.title = title
            this.content = content
        }
        // ... do something with `task`
    }
}

有什么更好的解决方案吗?提前感谢您的回复!

好吧,事实证明解决方案在 Ktorm 提供的文档中明确指出:

// extracted from org.ktorm.entity.Entity

/*
 * Besides of JDK serialization, the ktorm-jackson module also supports serializing entities in JSON format. This
 * module provides an extension for Jackson, the famous JSON framework in Java word. It supports serializing entity
 * objects into JSON format and parsing JSONs as entity objects. More details can be found in its documentation.
 */

实施 org.ktorm:ktorm-jackson:3.4.1 给我们带来了一个 Jackson 模块,在包 org.ktorm.jackson 中名为 KtormModule。我们接下来需要做的是将模块应用到我们的 springboot 应用程序中,如 class 注释 @Configuration:

@Configuration
class KtormConfig {
    @Bean
    fun ktormJacksonModule(): Module = KtormModule()

    // ... and other configurations if you like
}

就是这样。这样的KtormModule会在springboot应用启动时被jackson发现并应用,之后json和Ktorm Entities之间的编码和解码就没有问题了。