Kotlin 类型与可空类型和可选类型不匹配
我正在研究科特林和春天。我从基础开始。创建简单的CRUD应用程序并在其上进行试验 我有以下实体:Kotlin 类型与可空类型和可选类型不匹配,kotlin,Kotlin,我正在研究科特林和春天。我从基础开始。创建简单的CRUD应用程序并在其上进行试验 我有以下实体: @Entity @Table(name = "article") class Article( var title: String, var headline: String, var content: String, @ManyToOne var author: User? = null, var addedAt:
@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>
}
interface UserRepository:CrudRepository{
fun findByLogin(登录名:String):用户?
fun findByLastname(lastname:String):用户?
}
接口ArticleRepository:Crudepository{
有趣的findBySlug(slug:String):文章?
fun findAllByOrderByAddedAtDesc():Iterable
}
和我的休息控制器:
@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"
}
@PostMapping(“user/{userId}/newarticle”)
趣味createArticle(@RequestBody-article:article,@PathVariable-userId:Long){
val user=userRepository.findById(userId)
article.author=user我发现了这个问题
我使用的是Spring原生的findById(userId)
,它返回可选类型。它与Kotlin类型不兼容
我应该使用Kotlin的userRepository.findByIdOrNull(userId)
更多信息可以在优秀的文章中找到。findById(userId)
此方法返回什么?它返回user={Optional@111}在它里面,还有另一个名为value的属性,它实际上包含用户本身。