Jac*_*Zhu 6 mongodb spring-data kotlin spring-data-mongodb
环境:Spring-boot 2.1.2.RELEASE、Spring-data 2.1.4.RELEASE、Kotlin 1.2.x ~ 1.3.x、Mongodb。
我定义了一个模型类,如:
@Document
class MeAccount : Setting() {
lateinit var id: String
val accountEntries = listOf<BankAccount>()
}
Run Code Online (Sandbox Code Playgroud)
当我试图从 mongodb 读取这个模型时,我得到了异常堆栈跟踪:
java.lang.UnsupportedOperationException: No accessor to set property private final java.util.List com.xxx.MeCustodianAccount.accountEntries!
at com.xxx.MeCustodianAccount_Accessor_fs514j.setProperty(Unknown Source)
at org.springframework.data.mapping.model.ConvertingPropertyAccessor.setProperty(ConvertingPropertyAccessor.java:61)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.readProperties(MappingMongoConverter.java:378)
Run Code Online (Sandbox Code Playgroud)
请注意,该代码适用于 spring-boot 1.5.x 和 spring-data 1.x。
我能做些什么来解决这个问题?下面似乎有很多类似的异常报告:
Spring Boot 2.1.0 安全性更改与 kotlin 数据类?
https://github.com/arangodb/spring-data/issues/123
https://github.com/spring-projects/spring-boot/issues/15698
[已解决] 回退到 Spring-boot 2.0.x 和 spring-data-commons 2.0.x 后有效。将在未来的升级计划中排除 2.1。
Mic*_*ski 10
2.1 中的 Spring 数据。改变了它处理实体中最终字段的方式。它不再使用反射来覆盖字段的不变性,这通常是好的。有几种方法可以解决这个问题。
它们在此处描述:https : //jira.spring.io/browse/DATACMNS-1374?focusedCommentId=182289&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-182289
以下是 Spring 小伙伴们的推荐:
- 添加@PersistenceConstructor 来构造设置不可变字段的实体。
- 添加凋灵方法 (MyEntity withXxx(...)) 以创建一个包含更改的属性值的新实例。
- 或者:使用 Kotlin 的数据类功能。这基本上与凋灵方法相同。
所以你应该像这样工作:
@Document
data class MeAccount(val id: String, val accountEntries: List<Price>) : Setting()
Run Code Online (Sandbox Code Playgroud)