我正在研究 Kotlin 和 Spring。我从基础开始。创建简单的 CRUD 应用程序并对其进行实验。
我有这些实体:
@Entity
@Table(name = "article")
class Article(
var title: String,
var headline: String,
var content: String,
@ManyToOne var author: User? = null,
var addedAt: LocalDateTime = LocalDateTime.now(),
var slug: String = title.toSlug(),
@Id @GeneratedValue var id: Long? = null)
@Entity
@Table(name = "user")
class User(
var login: String,
var firstname: String,
var lastname: String,
var description: String? = null,
@Id @GeneratedValue var id: Long? = null)
我有这些存储库:
interface UserRepository : CrudRepository<User, Long> {
fun findByLogin(login: String): User?
fun findByLastname(lastname: String): User?
}
interface ArticleRepository : CrudRepository<Article, Long> {
fun findBySlug(slug: String): Article?
fun findAllByOrderByAddedAtDesc(): Iterable<Article>
}
还有我的休息 Controller :
@PostMapping("user/{userId}/newarticle")
fun createArticle(@RequestBody article: Article, @PathVariable userId: Long) {
val user = userRepository.findById(userId)
article.author = user <-- Type Mismatch
repository.save(article)
var stophere = "what"
}
当我尝试保存文章(其余 Controller )时,在这一行article.author = user
我收到以下错误:
类型不匹配:
必填:用户?
发现:可选
我尝试寻找解决方案,我认为它与 Nullable 值有关,但我无法弄清楚。 看来Spring返回了Java可选,而Kotlin不需要。
最佳答案
我发现了问题。
我使用的是 Spring native findById(userId)
,它返回可选类型。与 Kotlin 类型不兼容。
我应该使用 Kotlin 的 userRepository.findByIdOrNull(userId)
。
更多信息可以在this中找到优秀的文章。
关于kotlin - 类型与可空类型和可选类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58973377/