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?
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.
Related
I have a Kotlin SpringBoot project. It's a relatively simple API that persists data to a Postgres JsonB database.
I am using the #TypeDef annotation on my entity class, but after upgrading to SpringBoot Version 3.0 with hibernate-core:6.1.7.Final
this annotation is no longer available.
Here is my entity class::
import com.vladmihalcea.hibernate.type.json.JsonBinaryType
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.Table
import org.hibernate.annotations.Type
import org.hibernate.annotations.TypeDef // not available with latest hibernate-core
import java.io.Serializable
import java.security.SecureRandom
import kotlin.math.abs
#Entity
#Table(name = "myTable")
#TypeDef(name = "jsonb", typeClass = JsonBinaryType::class) // not available :(
data class RecommendationEntity(
#Id
open var id: Long = abs(SecureRandom().nextInt().toLong()),
#Type(type = "jsonb")
#Column(columnDefinition = "jsonb")
var data: MyModel
)
data class MyModel(
// nothing special just a POJO
) : Serializable
And here is my build.gradle.kts::
plugins {
id("XXXXXXXXXX.gradle-spring-boot") version "5.0.1" // in house plugin thatcopies 3.0.2
kotlin("jvm") version "1.8.10"
kotlin("plugin.jpa") version "1.8.20-Beta"
kotlin("plugin.spring") version "1.8.20-Beta"
}
jacoco.toolVersion = "0.8.8"
configurations {
testImplementation { exclude(group = "org.junit.vintage") }
}
testSets {
"testSmoke"()
}
// allOpen {
// annotations("javax.persistence.Entity")
// }
val springDocVersion = "1.6.14"
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-webflux")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
implementation("org.springframework.boot:spring-boot-starter-actuator:3.0.1")
implementation("com.deepoove:poi-tl:1.12.1") {
// exclude apache.xmlgraphics batik due to vulnerabilities when imported with poi-tl
exclude("org.apache.xmlgraphics", "batik-codec")
exclude("org.apache.xmlgraphics", "batik-transcoder")
}
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.flywaydb:flyway-core:9.11.0")
implementation("org.postgresql:postgresql:42.5.1")
implementation("org.springdoc:springdoc-openapi-webmvc-core:$springDocVersion")
implementation("org.springdoc:springdoc-openapi-ui:$springDocVersion")
implementation("org.springdoc:springdoc-openapi-kotlin:$springDocVersion")
implementation("org.springdoc:springdoc-openapi-data-rest:$springDocVersion")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
implementation("com.github.doyaaaaaken:kotlin-csv-jvm:1.7.0")
implementation("com.vladmihalcea:hibernate-types-52:2.21.1")
// implementation("org.hibernate:hibernate-core:5.6.3.Final")
// https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core
implementation("org.hibernate.orm:hibernate-core:6.1.7.Final")
testImplementation("org.awaitility:awaitility-kotlin:4.2.0")
testImplementation("org.mock-server:mockserver-netty:5.15.0")
testImplementation("io.projectreactor:reactor-test")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test")
testImplementation("org.junit.jupiter:junit-jupiter-params")
testImplementation("io.jsonwebtoken:jjwt:0.9.1")
testImplementation("com.natpryce:hamkrest:1.8.0.1")
testImplementation("org.flywaydb.flyway-test-extensions:flyway-spring-test:7.0.0")
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(18))
}
}
tasks {
withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions {
jvmTarget = "18"
}
}
}
tasks.test {
finalizedBy(tasks.jacocoTestReport)
}
tasks.jacocoTestReport {
dependsOn(tasks.test)
reports {
xml.required.set(true)
}
}
val SourceSet.kotlin: SourceDirectorySet
get() = project.extensions.getByType<org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension>().sourceSets.getByName(
name
).kotlin
sourceSets {
create("functional-test") {
kotlin.srcDirs("src/functional-test")
compileClasspath += sourceSets["main"].output + configurations["testRuntimeClasspath"]
runtimeClasspath += output + compileClasspath + sourceSets["test"].runtimeClasspath
}
}
tasks.withType<Jar>() {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
What I've tried::
Using hibernate-core:5.6.3.Final instead of 6.1.7.Final where #TypeDef is available, but that gives the error -
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Class org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider does not implement the requested interface jakarta.persistence.spi.PersistenceProvider
Looking through the various options here - how to store PostgreSQL jsonb using SpringBoot + JPA? there isn't any help specific to upgrading to SpringBoot V3.0
I'm quite stumped on this one, and am beginning to think that SpringBoot V3.0 doesn't support Postgres JsonB Nosql :(
Can anybody help me with a solution? Or perhaps confirm whether Postgres JsonB Nosql is indeed not supported in the new SpringBoot version?
Thanks
I found the solution here - https://github.com/vladmihalcea/hypersistence-utils/issues/367#issuecomment-1398737096
I bumped the version of my hibernate-types dependency implementation("com.vladmihalcea:hibernate-types-60:2.21.1")
And made changes to my entity class as recommended -
#Entity
#Table(name = "myTable")
// #TypeDef(name = "jsonb", typeClass = JsonBinaryType::class)
data class MyEntity(
#Id
open var id: Long = abs(SecureRandom().nextInt().toLong()),
// #Type(type = "jsonb")
// #Column(columnDefinition = "jsonb")
#Type(JsonType::class)
#Column(columnDefinition = "jsonb")
var data: MyModel
)
And now the issue is gone!
My application.kt file is as below:
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this)
}
override fun registerWith(registry: PluginRegistry?) {
io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin.registerWith(registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
}
error I am getting:
Cannot access 'com.google.firebase.messaging.zzf' which is a supertype
of 'io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService'.
Check your module classpath for missing or conflicting dependencies
the line where the error is FlutterFirebaseMessagingService.setPluginRegistrant(this).
my android/build.gradle file have below code for the implementation:
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath 'com.google.gms:google-services:4.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
I have tried to search a lot but still stuck with this issue. whats wrong here ?
Try this
In android/build.gradle add classpath 'com.google.gms:google-services:4.3.3'
In android/app/build.gradle add implementation "com.google.firebase:firebase-messaging:20.1.0"
OR
Try this
override fun registerWith(registry: PluginRegistry?) {
registry?.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin");
}
I am trying to run a springboot application on embedded Tomcat server in Eclipse. The project is added successfully to the server but it never starts.
My application code is below:
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.boot.Banner;
#SpringBootApplication
#ImportResource("classpath:simple-camel.xml")
public class CamelApplication {
private static final String DEFAULT_XML_ROUTE_CONFIG_FILES = "classpath:/routes/*.xml";
public static void main(String[] args) {
System.out.println("********************* inside the project ******************");
SpringApplication app = new SpringApplication(CamelApplication.class);
app.setDefaultProperties(getDefaultProperties());
app.run(args);
}
private static Properties getDefaultProperties() {
Properties props = new Properties();
props.setProperty("camel.springboot.main-run-controller", "true");
return props;
}
}
My build.gradle is below:
plugins {
id 'groovy'
id 'java'
id "org.springframework.boot" version "2.2.6.RELEASE"
}
group 'com.firas'
version '1.0-SNAPSHOT'
apply plugin: "org.springframework.boot"
apply plugin: "java"
repositories {
mavenCentral()
}
dependencies {
compile "org.apache.camel:camel-bom:2.25.0"
compile "org.apache.camel:camel-core:2.25.0"
compile "org.apache.camel:camel-spring-boot-dependencies:2.25.0"
compile "org.apache.camel:camel-spring-boot-starter:2.25.0"
compile "org.springframework:spring-aop:4.0.4.RELEASE"
compile "org.springframework:spring-context:4.0.4.RELEASE"
compile "org.springframework:spring-tx:4.0.4.RELEASE"
compile "org.apache.camel.springboot:camel-timer-starter:2.25.0"
compile "org.springframework.boot:spring-boot-starter-tomcat:2.2.6.RELEASE"
testCompile group: 'junit', name: 'junit', version: '4.13'
}
springBoot {
mainClassName = 'CamelApplication'
}
bootJar {
mainClassName = 'CamelApplication'
manifest {
attributes 'Start-Class': 'CamelApplication'
}
}
and below is a screen shot of my Deployment Assembly configuration:
Any hints or guidance on how to fix it? I am not seeing any errors in the log so I am flying blind here.
I am using Ionic.
Cordova CLI: 6.4.0
Ionic Framework Version: 3.1.1
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 1.3.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: macOS Sierra
Node Version: v7.10.0
Xcode version: Xcode 8.3.2 Build version 8E2002
I get the following error:
core.es5.js:1084 ERROR Error: Uncaught (in promise): Error: Module build failed: Error: ENOENT: no such file or directory, open
'/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/ratingModel.js'
Error: Module build failed: Error: ENOENT: no such file or directory, open
'/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/ratingModel.js'
When I try access the following page:
review/review.ts
...
import { RatingModel } from '../model/ratingModel';
#IonicPage()
#Component({
templateUrl: 'review.html'
})
export class ReviewPage {
...
model/ratingModel.ts
import { Injectable } from "#angular/core";
import { PersonModel } from './personModel';
import { JobModel } from './jobModel';
#Injectable()
export class RatingModel {
public id: number = null;
public job: JobModel = null;
public review: string = null;
public rating: number = null;
public reviewDate: number = null;
public time: string = null;
public person: PersonModel = null;
public anonymous: number = null;
}
This was working until I changed my pages to use lazy loading.
review/review.module.ts
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ReviewPage } from './review';
import { ControlMessagesModule } from '../validation/controlMessages.module';
import { RatingComponentUpdateableModule } from '../utils/rating/ratingComponentUpdateable.module';
#NgModule({
declarations: [ReviewPage],
imports: [IonicPageModule.forChild(ReviewPage), ControlMessagesModule, RatingComponentUpdateableModule],
exports: [ReviewPage]
})
export class ReviewPageModule { }
UPDATE
I find the error occurs because of the following:
this.ratingModel = navParams.get('ratingModel');
if (!this.ratingModel) {
this.ratingModel = new RatingModel();
when I remove the new RatingModel() line, I don't get any errors.
How are you supposed to create a new RatingModel?
The problem here is you are making the model class an injectable.
#Injectable()
export class RatingModel {
You dont have to make a model class as injectable.
If you do need to do so, you will have to set it as a provider.
Or try to get an object from the explicit injector.
constructor(private injector: Injector) { }
//..
this.ratingModel = this.injector.get(RatingModel)
I tried to setup gradle in eclipse Luna for a simple spring boot application, but none of the jars are downloaded. Can anyone give me an idea of what I'm missing ?
I ran gradle clean build in the command line and it compiles successfully:
This is the content of my build.gradle file :
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.1.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'spring-boot'
jar {
baseName = 'sample'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
}
This is the content of the class with the controller:
package sample;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class SampleController {
#RequestMapping("/sample")
public String sampleIt(){
return "Hello! Welcome to Spring Boot Sample. ";
}
}
This is the class with the main function :
package sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class SampleApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(SampleApplication.class, args);
System.out.println(ctx.getDisplayName());
System.out.println("This is my first Spring Boot Example");
}
}
Answer from the comment:
It is necessary to install the gradle plugin and import the gradle project afterwards. (Don't forget to click the 'Build Model' button)