【问题标题】:Kotlin data class No String-argument constructor with spring data restKotlin 数据类 No String-argument constructor with spring data rest
【发布时间】:2018-10-16 17:19:37
【问题描述】:

我正在使用带有 Kotlin 的 Spring 数据休息,如果我使用数据类,则通过 uri 的关联将停止工作,并出现错误 no String-argument constructor/factory method to deserialize from String value

数据类

@Entity
data class Comment(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)     
    var id: Long = 0,
    var author: String? = null,
    var content: String? = null,

    @ManyToOne
    var post: Post? = null) {
}

如果我使用简单的类,则关联工作正常。

@Entity
class Comment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)     var id: Long = 0
    var author: String? = null
    var content: String? = null

    @ManyToOne
    var post: Post? = null
}

关联是通过 POST 请求 {"author":"John Doe","content":"Dummy Content", "post":"http://localhost:8080/post/33"} 完成的

知道为什么我在使用数据类时会出现此错误,我该怎么做才能通过 uri 使用关联创建并继续使用数据类?

【问题讨论】:

    标签: spring-boot kotlin spring-data-rest


    【解决方案1】:

    我做了一些调查,结果发现 Spring Data Rest 使用自定义 Jackson 模块将 JSON 反序列化为 JPA 实体:它使用 PersistentEntityJackson2Module 类并使用内部类 UriStringDeserializer 从实体 URI 引用解析具体实体, http://localhost:8080/post/33 在您的示例中。

    问题是,这种自定义反序列化仅在触发 Jackson 的“标准反序列化”时才会生效:使用空构造函数,然后使用 setter 解析和设置字段。在那一刻,UriStringDeserializer 将字符串转换为具体实体 - 您的示例的 Post 实例。

    当您使用数据类时,该类既没有空的构造函数也没有设置器,因此在 Jackson 的 BeanDeserializer#deserializeFromObject 方法中,它分支到 if (_nonStandardCreation) 为真,从那里调用进入 BeanDeserializerBase#deserializeFromObjectUsingNonDefault ,但不是已经交给PersistentEntityJackson2Module了,由于构造函数参数和json值的类型不匹配而直接失败。

    您似乎需要创建一个功能请求才能实现它。如果您决定自己实现,向 BeanDeserializer 提供 _delegateDeserializer 可能是一个开始(不确定)。

    但是,我首先不知道 JPA 本身如何处理数据类 - 毕竟它跟踪实体状态更改,但数据类不能有状态更改。因此,毕竟可能无法使用数据类 - 最好记住。

    注意:您可能不能简单地扩展/覆盖PersistentEntityJackson2Module,因为它在RepositoryRestMvcConfiguration 中注册到多个bean

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 2018-10-08
      • 2020-02-27
      • 1970-01-01
      • 2020-03-01
      • 2017-12-08
      • 2020-12-16
      • 1970-01-01
      相关资源
      最近更新 更多