Light Blue Pointer
본문 바로가기
Developing/Trouble shooting

[Kotlin] Cannot set property id because no setter, no wither and it's not part of the persistence constructor

by Greedy 2024. 4. 25.

🚩에러

2024-04-25T22:52:54.233+09:00 ERROR 21840 --- [core] [nio-8081-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.IllegalStateException: Cannot set property id because no setter, no wither and it's not part of the persistence constructor public kpring.chat.chatroom.model.ChatRoom()] with root cause java.lang.IllegalStateException: Cannot set property id because no setter, no wither and it's not part of the persistence constructor public kpring.chat.chatroom.model.ChatRoom()

 

이런 에러가 떴다

 

⛳ 해결

Model 의 id를 val에서 var로 변경해줌

 @Id
    val id: String? = null

 @Id
    var id: String? = null
@Document(collection = "chatrooms")
class ChatRoom(
    var members : MutableList<String>
){
    @Id
    var id: String? = null

    val createdAt: LocalDateTime = LocalDateTime.now()

    fun getUsers(): MutableList<String>{
        return members
    }

    fun addUsers(list : MutableList<String>){
        members.addAll(list)
    }

}

 

 

🔎원인

Kotlin에서 val로 선언할 시 Java의 final로 변환되는데 

Spring Data 2.1부터 immutable objects를 더 지원하고 final은 더 이상 지원하지 않아 발생하는 문제이다

 

읽어보면 좋을 글
https://www.geeksforgeeks.org/final-vs-immutability-java/
https://discuss.kotlinlang.org/t/kotlin-val-var-vs-java-final-advantage/22908