Can't use the added function in Repository - spring

I'm using Spring Data Neo4j 2.4.4 for my project. This is some in project:
User:
UserRepository:
I can still use the built-in functions in Repository such as save(), findAll(),... but when I add and use some functions, for example "existsByUsername", it has error:
11:53:26.562 [http-nio-8081-exec-1] WARN o.s.d.n.c.Neo4jPersistenceExceptionTranslator - Don't know how to translate exception of type class org.neo4j.driver.exceptions.NoSuchRecordException
Then, I try to add query for function, it is still
Could you help me to determine this error and give me a solution? Thank you!\
Updated:
I call API in Postman, I received this result while my DB has only 1 user:
{
"error": "Records with more than one value cannot be converted without a mapper.; nested exception is java.lang.IllegalArgumentException: Records with more than one value cannot be converted without a mapper."
}

As your exception states, no record is returned from Neo4j and thus it cannot be mapped to a Boolean.
Best would be to use Optional<User> and check with isPresent()
#Query("MATCH (n:User {username: $username}) RETURN n")
Optional<User> existsForUsername(String username);
That said, it is already handled by Spring Data without using a custom query :
boolean existsByUsername(String username);
Reference : https://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#appendix.query.method.subject

There is a rather obscure set of references on github site for the NEO4J Spring Data: here
It seems that the existsBy property was omitted. It is being fixed, but whether that has made it to the Spring Data repository is another matter. You don;t say which version of the Spring-boot-starter-neo4j you are using, but you may care to use this one and see if it works;
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-neo4j -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-neo4j</artifactId>
<version>2.4.4</version>
</dependency>

In general, the other answers here are right. But, if you're using Spring Boot 2.4.4, OGM is no longer supported. It now uses a model called SDN (or at least it was when it was under development). You may just have a dependency issue. Here's part of my Gradle build file, these should be all the dependencies you need:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
application
id("org.springframework.boot") version "2.4.4"
id("io.spring.dependency-management") version "1.0.10.RELEASE"
}
java.sourceCompatibility = JavaVersion.VERSION_11
configurations {
compileOnly {
extendsFrom(configurations.annotationProcessor.get())
}
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-data-neo4j")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-web")
}

Related

How to override a plugin dependency in a Gradle conventions plugin

I'm using Gradle's conventions as described here:
https://docs.gradle.org/current/samples/sample_convention_plugins.html
And in the convention plugin, I'm applying a plugin (io.freefair.gradle:lombok-plugin:6.5.1) however I now need to override a dependency that it uses (I need org.projectlombok:lombok:1.18.22 not 1.18.24)
I've tried this:
buildscript {
dependencies {
classpath 'org.projectlombok:lombok:1.18.22'
}
}
plugins {
id 'groovy-gradle-plugin'
}
...
dependencies {
implementation 'io.freefair.gradle:lombok-plugin:6.5.1'
...
implementation 'org.projectlombok:lombok:1.18.22'
}
But version 1.18.24 was used. I've also tried adding this to my build.gradle:
buildscript {
dependencies {
classpath 'org.projectlombok:lombok:1.18.22'
}
}
plugins {
id 'billforward.java-conventions'
}
but still 1.18.24 was used.
As an aside, the two underlying issues I'm trying to solve are:
https://github.com/freefair/gradle-plugins/issues/549 - Resolved in 6.5 of lombok-plugin
https://github.com/projectlombok/lombok/issues/3180 - Broken in 1.18.24 of lombok
The lombok version used by io.freefair.lombok can be customized by using the lombok extension property:
plugins {
id "io.freefair.lombok" version "6.5.1"
}
lombok.version = "1.18.22"
This is documented here: https://docs.freefair.io/gradle-plugins/6.5.1/reference/#_io_freefair_lombok_base
Adding lombok itself to the buildscript classpath (or the runtime classpath of your gradle plugin) will not do anything.

kotlin springboot jackson google gson. Jacshon still used

I know several issues have been raised on this topic, but why Jackson is still used to serialize and deserialize JSON whereas I've excluded it from everywhere : in the springboot application, in build.gradle.kts and set the preferred Json serializer in application.properties
When I "crash" this HTTP request for test driven purpose, I can see that the crash is due to jackson converter
class IronMaidenSourceApi {
companion object {
fun fetchIronMaidenSource(): ResponseEntity<DTOIronMaidenAPi> {
val uri = "http://localhost:3004/ironmaiden"
return RestTemplate().getForEntity(uri, DTOIronMaidenAPi::class.java) // <-- JACKSON still used here
}
}
}
error is :
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType
So how the hell can I totally exclude Jackson ?
Not in dependencies
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
developmentOnly("org.springframework.boot:spring-boot-devtools")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test")
implementation ("com.google.code.gson:gson:2.9.0")
}
preferred is set to GSon in application.properties
spring.jpa.open-in-view=false
server.port=7070
spring.http.converters.preferred-json-mapper=gson
exclude in main application
#SpringBootApplication(exclude = [JacksonAutoConfiguration::class])
You need to exclude the transitive dependency like this:
dependencies {
implementation('commons-beanutils:commons-beanutils:1.9.4') {
exclude group: 'commons-collections', module: 'commons-collections'
}
Look at your dependency tree to see which dependencies are pulling it in and exclude it from each.

IntelliJ does not pick up own spring configuration metadata

I'm having problems for IntelliJ to pickup custom spring configuration metadata with Gradle.
If I create a new Spring Boot project with the Initializer, include the Configuration Processor in the dependencies, on the Gradle task set the following tasks,
create a class with the content:
package com.example.demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
#Component
#ConfigurationProperties("mycustomconfig")
public class MyCustomConfig {
private String name;
public String getName() {
return name;
}
public MyCustomConfig setName(String name) {
this.name = name;
return this;
}
}
then IntelliJ complains in the class file "Spring Boot Configuration Annotation Processor not found in classpath", even though it is definitely on the classpath.
After running the application, there is a file generated in build/classes/java/main/META-INF/spring-configuration-metadata.json with the following content:
{
"groups": [
{
"name": "mycustomconfig",
"type": "com.example.demo.MyCustomConfig",
"sourceType": "com.example.demo.MyCustomConfig"
}
],
"properties": [
{
"name": "mycustomconfig.name",
"type": "java.lang.String",
"sourceType": "com.example.demo.MyCustomConfig"
}
],
"hints": []
}
But IntelliJ then complains in application.properties: Cannot resolve configuration property "mycustomconfig.name".
The same experiment works flawlessly with Maven. Is there anything I'm doing wrong?
I'm using IntelliJ 2018.3 Ultimate.
My build.gradle is:
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
Finally, I've found the cause of the issue.
The annotation processor outputs the spring-configuration-metadata.json to build/classes/java/main/META-INF`.
But: IntelliJ uses a different classpath for the resolvement. Going to Project structure/Modules/main module/Paths, you can see that for the compiler output is set to "use module compile output path" and points to out/production/classes. This is resolved from Gradle automatically; changing it will be reverted once you have any changes in Gradle.
I've found that there are two possibilites:
Configure the Spring Boot Annotation Processor manually in IntelliJ Preferences/Build, Execution, Deployment/Compiler/Annotation Processors, with the following settings:
This has the benefit, that you do not need to run a complete gradle build - Just compiling from IntelliJ works. Unfortunately, every user in the project seems to manually set this up.
The second possiblity is mentioned at at this Stack overflow question. Set this idea options in Gradle:
idea{
module{
inheritOutputDirs = false
outputDir = compileJava.destinationDir
testOutputDir = compileTestJava.destinationDir
}
}
This basically now uses one compiled target class both for IntelliJ as well as Gradle. There seem to be some caveats, though, as mentioned in the linked urls.
Not sure if you solved this but I just upgraded to 2018.3 Ultimate and ran into the same problem. I suspect it is an IntelliJ issue but regardless I solved it by adding the following line
implementation('org.springframework.boot:spring-boot-configuration-processor')
Just above the "annotationProcessor" line in my gradle file...
Hope that helps
If you are using Maven, adding this dependency would resolve the issue.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

How to use AspectJ with Grails 3

I would like to use AspectJ in my Grails 3.3.6 application. Spring AOP works very well but I need to use call pointcut designator which is not supported by Spring AOP.
This is my aspect file which is located under src/main/java
TestAspect.aj
public aspect TestAspect{
pointcut executeMethod(): call(* com.example..*.*(..));
before(): executeMethod(){
System.out.println("before " +thisEnclosingJoinPointStaticPart.getSignature().getName());
}
after(): executeMethod(){
System.out.println("after "+thisJoinPoint.getSignature().getName());
}
}
I tried gradle aspectj plugin and updated build.gradle as follows
build.gradle
buildscript {
repositories {
...
}
dependencies {
classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.6"
}
}
project.ext {
aspectjVersion = '1.9.1'
}
apply plugin:"java"
apply plugin: 'aspectj.gradle'
Application starts without any errors but my aspect is not working. Am I missing something ?
Using IntelliJ 2018.2.1 and Java 1.8.0_171
Thanks in advance

Spring Data ElasticSearch Can't Connect with ElasticSearch 5.5.0

Am new to ElasticSearch...
Really love the API (especially ElasticsearchTemplate & supporting Unit Tests)...
Was following this example using ElasticSearch 5.5.0 (the following link has the full code inline and also available as a downloadable zip file):
https://www.mkyong.com/spring-boot/spring-boot-spring-data-elasticsearch-example/
maven dependencies:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
EsConfig:
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.mkyong.book.repository")
public class EsConfig {
#Value("${elasticsearch.host}")
private String EsHost;
#Value("${elasticsearch.port}")
private int EsPort;
#Value("${elasticsearch.clustername}")
private String EsClusterName;
#Bean
public Client client() throws Exception {
Settings esSettings = Settings.settingsBuilder()
.put("cluster.name", EsClusterName)
.build();
//https://www.elastic.co/guide/en/elasticsearch/guide/current/_transport_client_versus_node_client.html
return TransportClient.builder()
.settings(esSettings)
.build()
.addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName(EsHost), EsPort));
}
#Bean
public ElasticsearchOperations elasticsearchTemplate() throws Exception {
return new ElasticsearchTemplate(client());
}
}
src/main/resources:
elasticsearch.clustername = mkyong-cluster
elasticsearch.host = localhost
elasticsearch.port = 9300
When issuing the following, either:
mvn spring-boot:run
or
mvn clean test
stdout:
Caused by: NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{127.0.0.1}{127.0.0.1:9300}]]
at org.elasticsearch.client.transport.TransportClientNodesService.ensureNodesAreAvailable(TransportClientNodesService.java:326)
at org.elasticsearch.client.transport.TransportClientNodesService.execute(TransportClientNodesService.java:223)
at org.elasticsearch.client.transport.support.TransportProxyClient.execute(TransportProxyClient.java:55)
Also, get the following in my ElasticSearch 5.5.0 engine's stdout:
[2017-07-23T02:48:46,135][WARN ][o.e.t.n.Netty4Transport ] [vY7jxpr] exception caught on transport layer [[id: 0xa7e950be, L:/127.0.0.1:9300 - R:/127.0.0.1:60190]], closing connection
java.lang.IllegalStateException: Received message from unsupported version: [1.0.0] minimal compatible version is: [5.0.0]
at org.elasticsearch.transport.TcpTransport.messageReceived(TcpTransport.java:1379) ~[elasticsearch-5.5.0.jar:5.5.0]
at org.elasticsearch.transport.netty4.Netty4MessageChannelHandler.channelRead(Netty4MessageChannelHandler.java:74) ~[transport-netty4-5.5.0.jar:5.5.0]
Is there any way to use Spring Data ElasticSearch with ElasticSearch 5.5.0 engine?
If so, how would the connection be implemented?
I am using the Elastic Search Java client provided by Elastic Search and am able to connect and create indices on ElasticSearch 5.5.0 but really wish I could use the power of this library.
Spring Boot 1.5.1 does not support ElasticSearch 5.x (the article you provided also says it). To make it possible to work with ElasticSearch 5.x you need to use a milestone of Spring Boot 2.
Try to configure your project with following dependencies:
# spring boot
compile 'org.springframework.boot:spring-boot:2.0.0.M2'
# elasticsearch
compile 'org.elasticsearch:elasticsearch:5.5.0'
compile 'org.elasticsearch.client:transport:5.5.0'
# spring-data-elasticsearch for spring boot
compile 'org.springframework.boot:spring-boot-starter-data-elasticsearch:2.0.0.M2'
This should allow you to use all the goodies of Elasticsearch Java API ans spring-data-elasticsearch.
Update: Basic Gradle (v4.0.1) configuration would look like (build.gradle file):
buildscript {
ext {
springBootVersion = '2.0.0.M2'
}
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/libs-snapshot' }
maven { url 'http://repo.spring.io/milestone/' }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
apply plugin: 'java-library'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
jar {
baseName = 'elastic'
version = '0.0.1'
}
repositories {
mavenCentral()
jcenter()
maven { url 'https://repo.spring.io/libs-snapshot' }
maven { url 'http://repo.spring.io/milestone/' }
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-logging'
compile 'org.springframework.boot:spring-boot-starter-data-elasticsearch'
compile 'org.elasticsearch:elasticsearch:5.4.1'
compile 'org.elasticsearch.client:transport:5.4.1'
compile 'com.google.guava:guava:20.0'
testCompile 'junit:junit:4.12'
}

Resources