Issue
I have a problem when I try to use a MongoRepository. This is my Document class:
package model
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
@Document
class Product (@Id val name: String, var desc: String, var price: Double) {
var pictureCategory: String? = null
}
This is the repository:
package model.repositories
import model.Product
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository
@Repository
interface ProductRepository : MongoRepository <Product, String>
and this is the file where I have the compile error:
package controllers
import model.Product
import model.repositories.ProductRepository
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
@Controller
@RequestMapping("/product")
class ProductController {
@PostMapping("")
fun addProduct(@RequestBody newProduct: Product){
ProductRepository.save() //Unresolved reference: save <----------------------
}
}
I tried to performe and invalidate/restart but nothing is changed.
This is my build.gradle.kts file:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.4.3"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.4.30"
kotlin("plugin.spring") version "1.4.30"
kotlin("plugin.jpa") version "1.4.30"
}
group = "com.example"
version = "1.0.0"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
Maybe some dependencies that I have to add?
Solution
You are supposed to inject your repository in the REST controller, not using the static "save" method.
See : https://spring.io/guides/tutorials/rest/ for example.
Answered By - Anthony Chatellier