fastjson | FASTJSON 2.0.x has been released faster and more secure | JSON Processing library
kandi X-RAY | fastjson Summary
Support
Quality
Security
License
Reuse
- Build JavaBeanInfo from given class .
- Deserialize field information .
- Scan a date in ISO8601 format .
- Gets an object writer .
- Write a string with double quotes .
- Generate write as array .
- tokenize object
- Scan a field name .
- Get the value of a property
- Writes the value of the property .
fastjson Key Features
fastjson Examples and Code Snippets
Trending Discussions on fastjson
Trending Discussions on fastjson
QUESTION
I have a web socket handler inherited from AbstractWebSocketHandler
that handles text messages. My DTOs use javax.validation.constraints
for validation. So, in my REST endpoints, I simply can use the @Valid
annotation to invoke the validator. However, as far as I know, this annotation is not usable in my web socket handler. How can I invoke the SpringBoot validator programmatically without this annotation?
Besides, is it possible to use the SpringBoot de-serializer for messages instead of JSON.parseObject
?
Example:
import javax.validation.constraints.NotBlank;
import lombok.Data;
@Data
class CustomMessage {
@NotBlank
private String text;
}
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {
@Override
protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
// Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
log.debug("Received valid message {}", customMessage)
}
}
ANSWER
Answered 2021-Nov-23 at 04:53You will use a Validator
to fill a list of ConstraintViolation
. An example could looks like this :
public abstract class GenericService {
protected Validator validator;
protected void validateDomainRecord(T object, String message) {
Set> violations = validator.validate(object);
if(!violations.isEmpty()) {
throw new ConstraintViolationException(message, violations);
}
}
}
In your case, your code will looks something like this :
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
@Component
@Slf4j
public class MyCustomWebSocketHandler extends AbstractWebSocketHandler {
private Validator validator;
@Override
protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
CustomMessage customMessage = JSON.parseObject(message.getPayload(), CustomMessage.class);
// Validate the message according to javax.validation annotations and throw MethodArgumentNotValidException if invalid
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
Set> violations = validator.validate(customMessage);
if(!violations.isEmpty()) {
throw new ConstraintViolationException(message, violations);
}
log.debug("Received valid message {}", customMessage)
}
}
Take look a this good tutorial for more details. I guess it is also possible to customize your validation and your exception too.
QUESTION
I have tried everything I could find from StackOverflow
to make this problem right but none of them succeeded.
The strange thing is : I can use lambda such as
activity.runOnUiThread(() -> {
activity.startActivity(intent);
});
and stream like this
activity.getPackageManager().getInstalledPackages(0).stream().collect(Collectors.toList())
but this will fail :
activity.getPackageManager()
.getInstalledPackages(0)
.stream()
.filter(e -> e.packageName.contains("com"))
.collect(Collectors.toList())
plugins {
id 'com.android.application'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.mylearn.simplesender"
minSdk 25
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
viewBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.2'
implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.78'
implementation group: 'com.google.guava', name: 'guava', version: '31.0.1-android'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
and also, here is my Gradle setting in Android Studio
here is my compile setting in Android Studio
It shows an unreadable error, and when I debug this expression in the watcher shows :
Compilation failed:
-source 1.6 中不支持 lambda 表达式
(请使用 -source 8 或更高版本以启用 lambda 表达式)
which means I'm using source version 1.6, and it does not support lambda expression and told me to use source 8 or higher to enable lambda expression.
But I'm already in java 11, how could this happen?
ANSWER
Answered 2021-Nov-02 at 05:21go to App level build.gradle>
then put this code in android {} block
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
after this your code look like this
android {
compileSdkVersion 31
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "in.chikuai.example"
minSdkVersion 19
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
QUESTION
In my case, I have my signature key and I have generated the apk with function menubuild--->generate signed Bundle/Apk
Here are the steps how I generate this apk:
step 1:
step 2:
finally:
When I put this generated release apk into my real device, it will work well.
But when I tried to send this apk to my application center, it said that I don't have any signature file in this apk.
According to many issues found on google, I have noticed that there was actually no signature file in my apk at all. It seems that Android studio's build--->generate signed Bundle/Apk
didn't work at all, there was only a release with no signature that generated.
I'm quite new in android developing. I wonder if there are some mistakes in my gradle settings.
My application has 2 gradle.build
file like this picture:
the gradle.build
out side the app directory is :
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
and the gradle.build
file inside app directory is:
apply plugin: 'com.android.application'
android {
signingConfigs {
debug {
storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
storePassword '123123123'
keyAlias 'simple-sender-key'
keyPassword '123123123'
}
}
compileSdkVersion 30
buildToolsVersion "30.0.0"
defaultConfig {
applicationId "com.example.simplesender"
minSdkVersion 25
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.annotation:annotation:1.2.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.2'
implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.78'
implementation group: 'com.google.guava', name: 'guava', version: '31.0.1-android'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
}
I don't know why I can't generate an apk with signature...
ANSWER
Answered 2021-Oct-28 at 02:25Thanks for @Raj Suvariya
and @Nitish
The problem was solved according to their kindness instructions. And how I solved this problem is showing below:
First of all I'm using AS of version
Android Studio Arctic Fox | 2020.3.1 Patch 3
If you are using the same AS, you won't find any options to select signing version when you trying to generate a signed apk with your signing key like this picture showing below (they all have these 2 options).
after finishing building, the APK can be run in my device an works just all right, but I cannot deploy it to app store because app store told me that I have no signature file in META-INF.
The solution is to Explicitly specify
the signing strategy like this in build.gradle
and here is the code. the important code is
v1SigningEnabled true
v2SigningEnabled true
here is my build.gradle
file
apply plugin: 'com.android.application'
android {
signingConfigs {
debug {
storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
storePassword 'xxx'
keyAlias 'simple-sender-key'
keyPassword 'xxx'
v1SigningEnabled true
v2SigningEnabled true
}
release {
storeFile file('D:\\CodeRepository\\app-key-store\\SimpleSender.jks')
storePassword 'xxx'
keyAlias 'simple-sender-key'
keyPassword 'xxx'
v1SigningEnabled true
v2SigningEnabled true
}
}
.....your other configs.....
}
Try run generate signed apk again, and problem solved, and deployment to app store succeed.
QUESTION
Today I'm using FastJson(https://github.com/alibaba/fastjson), the following is my demo code.
class User {
private final String name;
private final int age;
private final String birthday;
private String password;
public User(String name, int age, String birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public void setPassword(String pwd) {
this.password = pwd;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getBirthday() {
return birthday;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", birthday='" + birthday + '\'' +
", password='" + password + '\'' +
'}';
}
}
It will serialize the field which has getXXX method. I do not want to serialize the password, and I will call the getPassword() to get the password value.
I do not want to rename the method getPassword and update the variable password to public.
Does anyone know how to ignore a field when serializing this class?
ANSWER
Answered 2021-Jun-10 at 03:04@JSONField(serialze=false)
public String getPassword() {
return password;
}
QUESTION
I use @JSONField annotation for pointX and pointY, I want to change pointX to point_x! I want to pointX show like point_x! But it did not work! It always is pointX and pointY! but other field is ok!
My java bean like this!
@Data
public class PointListOutput {
@JSONField(name = "latest_area_point_list")
private List latestAreaPointList;
@Data
public static class Point {
@JSONField(name = "point_x")
private Float pointX;
@JSONField(name = "point_y")
private Float pointY;
}
}
my config
@Override
protected void configureMessageConverters(final List> converters) {
super.configureMessageConverters(converters);
// create FastJson converter
final FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
final List supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
converter.setSupportedMediaTypes(supportedMediaTypes);
// create configuration class
final FastJsonConfig config = new FastJsonConfig();
// update filter of response
config.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
converter.setFastJsonConfig(config);
converters.add(new ByteArrayHttpMessageConverter());
converters.add(converter);
}
Here is my http response, as you can see the pointX is pointX! not point_x!
{
"code": 1,
"message": "Success",
"data": [
{
"latest_area_point_list": [
{
"pointX": 1.1,
"pointY": 1.1
},
{
"pointX": null,
"pointY": 1.1
}
]
}
]
}
ANSWER
Answered 2021-May-24 at 06:06I resolved this, it cause by org.springframework.beans.BeanUtils.copyProperties
I used org.springframework.beans.BeanUtils.copyProperties
change DAO java bean to View java bean.
My Dao java bean
@Data
@DynamoDBTable(tableName = "xxxx")
public class PointPojo {
@DynamoDBAttribute(attributeName = "latest_area_point_list")
private List latestAreaPointList;
@Data
@DynamoDBDocument
public static class Point {
@DynamoDBAttribute(attributeName = "point_x")
private Float pointX;
@DynamoDBAttribute(attributeName = "point_y")
private Float pointY;
}
}
And PointPojo
did no hava @JSONField(name = "point_x")
after copyProperties
the Point
was not PointListOutput$Point
, it was PointPojo@Point
, and it did not hava @JSONField(name = "point_x")
So this is the root cause!
I use orika replace org.springframework.beans.BeanUtils.copyProperties
, it was perfect!
QUESTION
I'm having an error as the below when I'm starting my program.
AbstractMethodError org.springframework.boot.context.config.ConfigFileApplicationListener.supportsSourceType
This is after I have added the below to my pom file:
org.springframework.boot
spring-boot-maven-plugin
false
ZIP
The reason which I added this is for the purpose to externalize some of the libraries to directly reference to it from runtime classpath:
nohup java -cp MyProject.jar -Dloader.path=/path/lib/ org.springframework.boot.loader.PropertiesLauncher &
Full pom file:
4.0.0
parent proj
project
R2-1.0.0-SNAPSHOT
project
jar
3.7.0
1.7.9
1.8
project
project
R2-1.0.0-SNAPSHOT
com.h2database
h2
runtime
org.springframework.boot
spring-boot-starter-test
ch.qos.logback
logback-classic
${springboot.version}
test
org.apache.commons
commons-io
1.3.2
org.apache.axis2
axis2-transport-local
${axis2.version}
compile
org.apache.axis2
axis2-transport-http
${axis2.version}
compile
org.apache.axis2
axis2-xmlbeans
${axis2.version}
compile
org.apache.axis2
axis2-jaxws
jaxb-impl
com.sun.xml.bind
javax.xml.bind
jaxb-api
1.7.9
compile
org.apache.ws.commons.axiom
axiom-api
1.2.21
compile
org.apache.ws.commons.axiom
axiom-impl
1.2.21
compile
MyProject
org.springframework.boot
spring-boot-maven-plugin
false
ZIP
Parent Pom:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.8.RELEASE
parent proj
project
R2-1.0.0-SNAPSHOT
pom
project1
project2
project3
proj
proj
R2-1.0.0-SNAPSHOT
2.1.8.RELEASE
UTF-8
UTF-8
1.8
3.0.0-RC1
1.7.26
2.8.10
9.8.0-8
1.7.9
${java.version}
${java.version}
org.springframework.boot
spring-boot-dependencies
${springboot.version}
pom
import
org.apache.camel
camel-spring-boot-dependencies
${camel.version}
pom
import
org.springframework.boot
spring-boot-starter-activemq
org.apache.activemq
activemq-broker
org.apache.camel
camel-spring-boot-starter
org.apache.camel
camel-activemq
org.apache.activemq
activemq-broker
org.springframework.boot
spring-boot-configuration-processor
true
org.springframework.boot
spring-boot-starter-actuator
org.apache.activemq
activemq-broker
org.apache.activemq
activemq-pool
org.apache.logging.log4j
log4j-api
test
org.apache.logging.log4j
log4j-core
test
org.apache.logging.log4j
log4j-slf4j-impl
test
org.apache.logging.log4j
log4j-1.2-api
test
org.springframework.boot
spring-boot-starter-test
ch.qos.logback
logback-classic
test
org.apache.camel
camel-test-spring
test
org.springframework.boot
spring-boot-starter-jdbc
com.oracle.jdbc
ojdbc7
12.1.0.2
com.alibaba
fastjson
1.2.60
org.infinispan
infinispan-remote
9.1.7.Final
io.spring.platform
platform-bom
Brussels-SR4
pom
import
Screenshot of my error on runtime
Please help! Thanks
Spring boot version 2.1.8.RELEASE for all
Camel Spring Boot Context 5.1.9 RELEASE
I have found out ConfigurableApplicationContext is referencing spring-context-5.1.9.RELEASE
ANSWER
Answered 2021-Mar-25 at 06:00seems it's related to your config file
use -X flag with your maven command to see the full stack trace
mvn -X spring-boot:run
QUESTION
I have customized this JSON config file for a mod from the game Valheim. The mods make use of a Unity program in order to load the mods up and it shows a console log so you can find errors while loading the game with said mods. I am getting this constant error in the Unity console regarding the file, but cannot understand the error or find any errors in the files JSON formatting.
The error is as follows
[Info : BepInEx] Loading [Epic Loot 0.6.4]
[Error : Unity Log] Exception: Unrecognized token at index 14451
Stack trace:
fastJSON.JsonParser.ParseValue (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseArray (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseValue (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseObject (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseValue (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseArray (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseValue (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseObject (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.ParseValue (System.Char* p) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JsonParser.Decode (System.Type objtype) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.deserializer.ToObject (System.String json, System.Type type) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.deserializer.ToObject[T] (System.String json) (at <375de602811e45c183084f18a311bd14>:0)
fastJSON.JSON.ToObject[T] (System.String json) (at <375de602811e45c183084f18a311bd14>:0)
EpicLoot.EpicLoot.LoadJsonFile[T] (System.String filename) (at <626516c9d3e244fa8f8ddd6519f94bb9>:0)
EpicLoot.EpicLoot.InitializeConfig () (at <626516c9d3e244fa8f8ddd6519f94bb9>:0)
EpicLoot.EpicLoot.Awake () (at <626516c9d3e244fa8f8ddd6519f94bb9>:0)
UnityEngine.GameObject:AddComponent(Type)
BepInEx.Bootstrap.Chainloader:Start()
UnityEngine.Application:.cctor()"
ANSWER
Answered 2021-Apr-05 at 14:19What the error message is saying is that 14451th character is wrong (from the json parser's point of view).
This character index is not very helpful to me. So, to explore this further, I've removed the comments with a regex (in the regex101 link, click on "substitution" on the left panel to see the version without comments). [*]
Then I pasted the comment-less version in an online JSON parser.
The output is a bit more precise:
Parse error on line 368:
..., "Weight": 1 } }, { "Obje
----------------------^
Expecting ',', ']', got '}'
Find the line 368 by using some correct text editor like notepad++, and indeed there is something wrong here:
{
"Object": "Leech",
"Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
"Loot": [
{ "Item": "Tier2EnchantMats", "Weight": 1 } <--- line 368 without the comments
},
In my opinion, you wanted this instead :
{
"Object": "Leech",
"Drops": [ [0, 0], [1, 65], [2, 25], [3, 10] ],
"Loot": [
{ "Item": "Tier2EnchantMats", "Weight": 1 }
]
},
You forgot to close the array 'Loot' ! (closing bracket needed)
I'll let you repeat the process to check for other syntax errors.
Note: [*] Even though some JSON parsers may accommodate comments, the JSON specifications don't authorize them at all, as for this parser.
QUESTION
The default result of rendering FastJsonApi gem serialized_json like below:
render json: FlashcardSerializer.new(flashcards).serialized_json
would be something like this:
{
"data": [
{
"id": "1",
"type": "flashcard",
"attributes": {
"question": "why?",
"answer": "pretty good",
"slug": null
}
},
{
"id": "2",
"type": "flashcard",
"attributes": {
"question": "What is 0",
"answer": "it is 0",
"slug": null
}
}
]
}
I would rather add some extra information especially for pagination and I like the result to be something like this:
{
"data": [
{
"id": "1",
"type": "flashcard",
"attributes": {
"question": "why?",
"answer": "pretty good",
"slug": null
}
},
{
"id": "2",
"type": "flashcard",
"attributes": {
"question": "What is 0",
"answer": "it is 0",
"slug": null
}
},
"count":100,
"page":1,
]
}
I am aware of other available gems that manage pagination in API, and I know how to do it without Fastjson. The main issue here is that is there any way to get the aforementioned result from this gem without changing a lot in the code. Thanks
ANSWER
Answered 2021-Feb-27 at 07:55The desired document would be invalid according to the JSON API specification. You would need to include next and previous links in a link section. The current
and total_count
would belong in the meta section.
{
"data": [
{
"id": "1",
"type": "flashcard",
"attributes": {
"question": "why?",
"answer": "pretty good",
"slug": null
}
},
{
"id": "2",
"type": "flashcard",
"attributes": {
"question": "What is 0",
"answer": "it is 0",
"slug": null
}
},
]
"meta": {
"page": { "current": 1, "total": 100 }
},
"links": {
"prev": "/example-data?page[before]=yyy&page[size]=1",
"next": "/example-data?page[after]=yyy&page[size]=1"
},
}
Have a look at the JSON API specification before you continue designing the API.
You can pass these information into the serializer as an options argument
class FlashcardsController < ApplicationController
def index
render json: FlashcardSerializer.new(
flashcards, { links: {}, meta: { page: { current: 1 } }
).serialized_json
end
end
How you generate the data depends what you use to paginate.
If you design a new API, I would also recommend to use cursor based pagination rather than offset pagination because of it's limitations.
https://github.com/Netflix/fast_jsonapi#compound-document https://github.com/Netflix/fast_jsonapi/blob/master/spec/lib/object_serializer_spec.rb#L8-L32
QUESTION
As the title suggests, I met the StackOverFlow problem when I connect to Neo4j in Springboot with Mybatis. The CQL runs well in Neo4j desktop, but the api returns a 500 result with the same CQL in mapper.
The error message goes like:
2020-12-31 20:22:24.560 ERROR 31232 --- [nio-9090-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError: null
at java.io.WinNTFileSystem.normalizePrefix(WinNTFileSystem.java:186) ~[na:1.8.0_261]
at java.io.WinNTFileSystem.normalize(WinNTFileSystem.java:111) ~[na:1.8.0_261]
at java.io.WinNTFileSystem.normalize(WinNTFileSystem.java:93) ~[na:1.8.0_261]
at java.io.File.(File.java:279) ~[na:1.8.0_261]
at java.io.FilePermission$1.run(FilePermission.java:224) ~[na:1.8.0_261]
at java.io.FilePermission$1.run(FilePermission.java:212) ~[na:1.8.0_261]
at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_261]
at java.io.FilePermission.init(FilePermission.java:212) ~[na:1.8.0_261]
at java.io.FilePermission.(FilePermission.java:299) ~[na:1.8.0_261]
at sun.net.www.protocol.file.FileURLConnection.getPermission(FileURLConnection.java:228) ~[na:1.8.0_261]
at sun.net.www.protocol.jar.JarFileFactory.getPermission(JarFileFactory.java:166) ~[na:1.8.0_261]
at sun.net.www.protocol.jar.JarFileFactory.getCachedJarFile(JarFileFactory.java:136) ~[na:1.8.0_261]
at sun.net.www.protocol.jar.JarFileFactory.get(JarFileFactory.java:91) ~[na:1.8.0_261]
at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:122) ~[na:1.8.0_261]
at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:152) ~[na:1.8.0_261]
at java.net.URLClassLoader.getResourceAsStream(URLClassLoader.java:239) ~[na:1.8.0_261]
at java.lang.Class.getResourceAsStream(Class.java:2223) ~[na:1.8.0_261]
at org.neo4j.jdbc.DatabaseMetaData.(DatabaseMetaData.java:100) ~[neo4j-jdbc-driver-3.1.0.jar:na]
at org.neo4j.jdbc.http.HttpDatabaseMetaData.(HttpDatabaseMetaData.java:34) ~[neo4j-jdbc-driver-3.1.0.jar:na]
at org.neo4j.jdbc.http.HttpDatabaseMetaData.(HttpDatabaseMetaData.java:43) ~[neo4j-jdbc-driver-3.1.0.jar:na]
at org.neo4j.jdbc.http.HttpConnection.getMetaData(HttpConnection.java:105) ~[neo4j-jdbc-driver-3.1.0.jar:na]
at org.neo4j.jdbc.http.HttpConnection.getMetaData(HttpConnection.java:40) ~[neo4j-jdbc-driver-3.1.0.jar:na]
at com.zaxxer.hikari.pool.ProxyConnection.getMetaData(ProxyConnection.java:380) ~[HikariCP-3.4.5.jar:na]
at com.zaxxer.hikari.pool.HikariProxyConnection.getMetaData(HikariProxyConnection.java) ~[HikariCP-3.4.5.jar:na]
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getNextResultSet(DefaultResultSetHandler.java:256) ~[mybatis-3.5.2.jar:3.5.2]
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getNextResultSet(DefaultResultSetHandler.java:261) ~[mybatis-3.5.2.jar:3.5.2]
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getNextResultSet(DefaultResultSetHandler.java:261) ~[mybatis-3.5.2.jar:3.5.2]
at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getNextResultSet(DefaultResultSetHandler.java:261) ~[mybatis-3.5.2.jar:3.5.2]
(The last line was repeated hundreds of times)
Here are my configurations and code:
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.4.RELEASE
com.neo4j.dw
dw
0.0.1-SNAPSHOT
amazonMovies
Amazon Movies Data Warehouse
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-data-neo4j
org.springframework.boot
spring-boot-devtools
runtime
true
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.neo4j
neo4j-jdbc-driver
3.1.0
org.mybatis
mybatis
3.5.2
junit
junit
4.12
io.springfox
springfox-bean-validators
2.9.2
org.springframework.boot
spring-boot-configuration-processor
true
com.baomidou
mybatis-plus-boot-starter
3.4.0
org.springframework.boot
spring-boot-starter-freemarker
javax.validation
validation-api
2.0.1.Final
com.baomidou
mybatis-plus-generator
3.4.0
mybatis
org.mybatis
com.auth0
java-jwt
3.9.0
com.alibaba
fastjson
1.2.47
org.json
json
20190722
org.apache.httpcomponents
httpclient
org.bouncycastle
bcprov-jdk16
1.46
com.baomidou
mybatis-plus
3.4.0
org.springframework.boot
spring-boot-maven-plugin
com.neo4j.dw.DwApplication
org.springframework.boot
spring-boot-configuration-processor
org.springframework.boot
spring-boot-maven-plugin
true
mybatis_config.xml
application.yml
spring:
datasource:
driver-class-name: org.neo4j.jdbc.http.HttpDriver
url: jdbc:neo4j:http://localhost:7474
username: neo4j
password: ETL2020
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
type-aliases-package: com.neo4j.dw.Model
server:
port: 9090
TestController
package com.neo4j.dw.Controller;
import com.neo4j.dw.Model.User;
import com.neo4j.dw.Service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/hello")
public String hello(){
return "hello";
}
@GetMapping("/user")
public ArrayList getUsers() {
return testService.selectUsers();
}
}
TestServiceImpl
package com.neo4j.dw.Service.Impl;
import com.neo4j.dw.Mapper.TestMapper;
import com.neo4j.dw.Model.User;
import com.neo4j.dw.Service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestMapper testMapper;
@Override
public ArrayList selectUsers(){
return testMapper.selectUsers();
}
}
TestMapper
package com.neo4j.dw.Mapper;
import com.neo4j.dw.Model.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.ArrayList;
@Mapper
public interface TestMapper {
ArrayList selectUsers();
}
User
package com.neo4j.dw.Model;
import lombok.*;
import com.baomidou.mybatisplus.annotation.TableField;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Getter
@Setter
public class User {
@TableField("userId")
public String userId;
@TableField("profileName")
public String profileName;
}
TestMapper.xml
MATCH (n1)-[r]->(n2) RETURN count(*)
I'm new in Neo4j and Mybatis. Can anyone help me figure out how to fix this error? Thanks a million!
ANSWER
Answered 2020-Dec-31 at 15:28As far as I know, there is no MyBatis integration in:
- neither Spring Data Neo4j 5 (added via
spring-boot-starter-data-neo4j
in your POM, included up until Spring Boot 2.3) - nor Neo4j OGM (which is the library Spring Data Neo4j 5 is built upon).
If you want to get started, you should probably get started with Spring Data Neo4j 6 (aka SDN 6), i.e. the latest version of Spring Data Neo4j at the time of writing. If you upgrade Spring Boot to the latest version (2.4 at the time of writing), you will automatically get it.
You should probably start with the reference documentation of SDN 6. You also can find an example here.
As you will learn, you can get rid of MyBatis, SDN 6 (and 5 via Neo4j OGM) takes care of the mapping already.
QUESTION
I use the following configuration and code to create a spring boot application.
pom.xml:
jeecg-boot-parent
org.jeecgframework.boot
2.3.0
4.0.0
my-pm-project
org.jeecgframework.boot
jeecg-system-cloud-api
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
com.alibaba.cloud
spring-cloud-starter-alibaba-sentinel
org.jeecgframework.boot
jeecg-boot-base-common
org.springframework.boot
spring-boot-starter-data-mongodb
Controller:
package cn.my.pm.project.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import cn.my.pm.project.entity.Project;
import cn.my.pm.project.service.IProjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
@RestController
@RequestMapping("/project/project")
@Slf4j
public class ProjectController extends JeecgController {
@Autowired
private IProjectService projectService;
@GetMapping(value = "/list")
public Result queryPageList(Project project,
@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper queryWrapper = QueryGenerator.initQueryWrapper(project, req.getParameterMap());
Page page = new Page(pageNo, pageSize);
IPage pageList = projectService.page(page, queryWrapper);
return Result.OK(pageList);
}
@PostMapping(value = "/add")
public Result add(@RequestBody Project project) {
projectService.save(project);
return Result.OK("add!");
}
@PutMapping(value = "/edit")
public Result edit(@RequestBody Project project) {
projectService.updateById(project);
return Result.OK("edit!");
}
@DeleteMapping(value = "/delete")
public Result delete(@RequestParam(name="id",required=true) String id) {
projectService.removeById(id);
return Result.OK("delete!");
}
@DeleteMapping(value = "/deleteBatch")
public Result deleteBatch(@RequestParam(name="ids",required=true) String ids) {
this.projectService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("batch delete!");
}
@GetMapping(value = "/queryById")
public Result queryById(@RequestParam(name="id",required=true) String id) {
Project project = projectService.getById(id);
if(project==null) {
return Result.error("not found");
}
return Result.OK(project);
}
}
Service:
package cn.my.pm.project.service;
import cn.my.pm.project.entity.Project;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IProjectService extends IService {
}
ServiceImpl:
package cn.my.pm.project.service.impl;
import cn.my.pm.project.entity.Project;
import cn.my.pm.project.mapper.ProjectMapper;
import cn.my.pm.project.service.IProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@Service
@Slf4j
public class ProjectServiceImpl extends ServiceImpl implements IProjectService {
}
Mapper:
package cn.my.pm.project.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.my.pm.project.entity.Project;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Service;
public interface ProjectMapper extends BaseMapper {
}
ProjectMapper.xml:
Entity:
package cn.my.pm.project.entity;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecg.common.aspect.annotation.Dict;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
@Data
@TableName("my_info")
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
private java.lang.String id;
private java.lang.String myName;
private java.lang.String myType;
private java.lang.String myType;
private java.lang.String myManager;
private java.lang.String myInfo;
private java.lang.String myDetails;
private java.lang.String myImage;
}
Application:
package cn.my;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAnnotationProcessorAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroBeanAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication(exclude = {ShiroAnnotationProcessorAutoConfiguration.class, ShiroAutoConfiguration.class, ShiroBeanAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients
public class ProjectApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
But when I run the application,the error message is:
ERROR org.springframework.boot.SpringApplication:858 - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.my.pm.project.mapper.ProjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at cn.my.ProjectApplication.main(ProjectApplication.java:18)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.my.pm.project.mapper.ProjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
... 19 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.my.pm.project.mapper.ProjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
... 32 common frames omitted
Disconnected from the target VM, address: '127.0.0.1:64977', transport: 'socket'
How to fix it?
ANSWER
Answered 2020-Nov-18 at 06:08Spring's complaint is that you haven't defined a Bean of type ProjectMapper
, which it is saying that it needs to satisfy an Autowire request. Looking at your code, I don't see a definition for such a Bean in what you've shown us here.
The exact point of the problem is hidden, I'm guessing, because you aren't showing us the definition of the ServiceImpl
class. My guess is that that's where the actual reference is that Spring is trying to wire up. Apparently, the field name is baseMapper
.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install fastjson
You can use fastjson like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the fastjson component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page