Home > Mobile >  How to fix .UnsatisfiedDependencyException error in Spring?
How to fix .UnsatisfiedDependencyException error in Spring?

Time:10-13

I have the following code:

package com.example.demo

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table

@SpringBootApplication
class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}


@RestController
class MessageResource(var service: MessageService) {

    @GetMapping
    fun index(): List<Message> = service.findMessagesInDB()

    @PostMapping
    fun post(@RequestBody message: Message) {
        service.addMessageToDB(message)
    }
}


@Service
class MessageService(val db : MessageRepository) {

    fun findMessagesInDB(): List<Message> = db.findMessages()

    fun addMessageToDB(message: Message){
        db.save(message)
    }
}

@Repository
interface MessageRepository : CrudRepository<Message, String> {
    @Query("select * from messages")
    fun findMessages(): List<Message>
}


@Table(name ="MESSAGES")
@Entity
data class Message(@Id val id: String?, val text: String)

I am getting the following error. I couldn't figure out why.

java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.demo.MessageRepository.findMessages()!

Could someone help me with it? I followed this kotlin-Spring tutorial: https://kotlinlang.org/docs/jvm-spring-boot-restful.html#add-database-support

CodePudding user response:

It seems to me that a nativeQuery = true attribute is missing in your @Query. Try the following:

@Repository
interface MessageRepository : CrudRepository<Message, String> {
    @Query(value = "select * from messages", nativeQuery = true)
    fun findMessages(): List<Message>
}

Additionally, this custom @Query method seems unnecessary, since CrudRepository has a method (findAll()) that does exactly that.

  • Related