"invalid hexadecimal representation" for spring mongo data repository interface - mongodb

I have a repository interface as follows:
public interface ExcursionAttendeeRepository extends MongoRepository<ExcursionAttendee, String> {
ExcursionAttendee findByWorkflowItemId(String workflowItemId);
#Query("{ 'excursionEvent._id' : { '$oid' : ?0 } }")
List<ExcursionAttendee> findByExcursionId(String excursionId);
#Query("{ 'student._id' : {'$oid' : ?0} , 'excursionEvent._id' : { '$oid' : ?1 } }")
ExcursionAttendee findByStudentIdAndEventId(String studentId, String excursionId);
#Query("{ 'student._id' : { '$oid' : ?0 } }")
List<ExcursionAttendee> findByStudentId(String studentId);
}
While Bean creation spring throws following exception.
Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#0.1':
Cannot create inner bean '(inner bean)#5172829b' of type [org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter] while setting bean property 'messageListener';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#5172829b':
Cannot resolve reference to bean 'productDetailsEventConsumer' while setting bean property 'delegate';
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productDetailsEventConsumer': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cinglevue.veip.service.excursion.ExcursionAttendeeService com.cinglevue.veip.service.erp.impl.ProductDetailsEventConsumer.excursionAttendeeService;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'excursionAttendeeServiceImpl': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cinglevue.veip.repository.excursion.ExcursionAttendeeRepository com.cinglevue.veip.service.excursion.impl.ExcursionAttendeeServiceImpl.excursionAttendeeRepository;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'excursionAttendeeRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: [_param_0]
Ideally this exceptions should get thrown when trying to initialise a ObjectId with an invalid string. [ code ]. I'm wondering how the class gets initialised in order for an exception to get thrown while bean creation. Any tips on this?

I ran into the same question and following should work.
#Query("{ 'student' : { '$id': ?0 } }")
List<ExcursionAttendee> findByStudentId(String studentId);
If it is a DBRef it should be like this, (This is what im using after the same issue, I have a DBRef in my case)
#Query("{ 'student': {'$ref': 'user', '$id': ?0} }")
List<ExcursionAttendee> findByStudentId(String studentId);
For DBRef this should work as well,
List<ExcursionAttendee> findByStudentId(String studentId);
I found the answer from here.

#Query("{ 'student._id' : {'$oid' : ?0} , 'excursionEvent._id' : { '$oid' : ?1 } }")
ExcursionAttendee findByStudentIdAndEventId(String studentId, String excursionId);
You don't need to specify #Query if you follow spring-data method naming conventions.

The query should work with
#Query("{ 'student._id' : ?0} , 'excursionEvent._id' : ?1 } }")
Reference: https://jira.spring.io/si/jira.issueviews:issue-html/DATAMONGO-1070/DATAMONGO-1070.html

Related

Compound index does not currently support nested documents or arrays in Azure Cosmos MongoDB

Connecting Javers API with Azure Cosmos MongoDB
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JaversFromStarter' defined in class path resource [com/test/config/JaversMongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.javers.core.Javers]: Factory method 'javers' threw exception; nested exception is com.mongodb.MongoCommandException: Command failed with error 115 (CommandNotSupported): 'Compound index does not currently support nested documents or arrays.' on server azurecosommongo:10255. The full response is { "ok" : 0.0, "errmsg" : "Compound index does not currently support nested documents or arrays.", "code" : 115, "codeName" : "CommandNotSupported" }
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:456) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1305) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 22 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.javers.core.Javers]: Factory method 'javers' threw exception; nested exception is com.mongodb.MongoCommandException: Command failed with error 115 (CommandNotSupported): 'Compound index does not currently support nested documents or arrays.' on server azurecosommongo:10255. The full response is { "ok" : 0.0, "errmsg" : "Compound index does not currently support nested documents or arrays.", "code" : 115, "codeName" : "CommandNotSupported" }
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 35 common frames omitted
Caused by: com.mongodb.MongoCommandException: Command failed with error 115 (CommandNotSupported): 'Compound index does not currently support nested documents or arrays.' on server azurecosommongo:10255. The full response is { "ok" : 0.0, "errmsg" : "Compound index does not currently support nested documents or arrays.", "code" : 115, "codeName" : "CommandNotSupported" }
at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:179) ~[mongodb-driver-core-3.8.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:293) ~[mongodb-driver-core-3.8.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:255) ~[mongodb-driver-core-3.8.2.jar:na]
Below is Configuration which I added to support the connection. But I am getting an exception on app startup only. I am able to connect with simple MongoDB but with Cosmos API I am getting the
Compound index does not currently support nested documents or arrays.
#Autowired
private JaversMongoProperties javersMongoProperties;
#Autowired
private MongoDbFactory mongoDbFactory; //from spring-boot-starter-data-mongodb
#Autowired
#Qualifier("javersMongoClientOptions")
private Optional<MongoClientOptions> mongoClientOptions;
#Bean(name = "JaversFromStarter")
#ConditionalOnMissingBean
public Javers javers() {
logger.info("Starting javers-spring-boot-starter-mongo ...");
MongoDatabase mongoDatabase = initJaversMongoDatabase();
MongoRepository javersRepository = createMongoRepository(mongoDatabase);
return JaversBuilder.javers()
.registerJaversRepository(javersRepository)
.withProperties(javersMongoProperties)
.withObjectAccessHook(javersMongoProperties.createObjectAccessHookInstance())
.build();
}
private MongoDatabase initJaversMongoDatabase() {
if (!javersMongoProperties.isDedicatedMongodbConfigurationEnabled()) {
MongoDatabase mongoDatabase = mongoDbFactory.getDb();
logger.info("connecting Javers to Mongo database '{}' configured in spring.data.mongodb properties",
mongoDatabase.getName());
return mongoDatabase;
} else {
MongoDatabase mongoDatabase = JaversDedicatedMongoFactory.createMongoDatabase(javersMongoProperties, mongoClientOptions);
logger.info("connecting Javers to Mongo database '{}' configured in javers.mongodb properties",
mongoDatabase.getName());
return mongoDatabase;
}
}
You are using wrong method to create MongoRepository. You should use this one:
/**
* MongoRepository compatible with Amazon DocumentDB.
* <br/>
*
* Compound index on <code>commitProperties</code> isn't created.
* <br/><br/>
*
* See functional differences.
*/
public static MongoRepository mongoRepositoryWithDocumentDBCompatibility(MongoDatabase mongo, int cacheSize) {
return new MongoRepository(mongo, cacheSize, DOCUMENT_DB);
}

Unsatisfied dependency Exception

I have a spring boot application where I need to store image into a local folder and its details like id,name and path in db.I done this with no problem. Now I want to edit the name in the folder as well as in db. I succeeded in renaming the file in the folder and i want to rename in db as well. I have written code for this but i got error like unsatisfied dependency. In my controller
#PutMapping("/updateFile")
public String updateFile(#RequestParam String oldFileName,#RequestParam String newFileName,#RequestParam UUID imageId,#RequestParam ImageModel imageModel) throws IOException {
// UUID Id=UUID.fromString(imageId);
imgserv.updateImageData(imageId, imageModel);
return fileStorageService.updateFile(oldFileName, newFileName);
}
and in service implementation
#Override
public String updateImageData(UUID imageId, ImageModel imageModel) {
ImageModel imageData = imageRepo.findImageById(imageId);
if (imageId == null) {
return "Image Data Not Found";
}
imageData.setImageName(imageModel.getImageName());
imageRepo.save(imageData);
return "Image Details Updated Successfully!";
}
and my Repository class
#Repository("imageRepo")
public interface ImageRepo extends MongoRepository<ImageModel, UUID> {
ImageModel findImageById(UUID imageId);
}
and my error code is like
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileController': Unsatisfied dependency expressed through field 'imgserv'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'imgserv': Unsatisfied dependency expressed through field 'imageRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'imageRepo': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property id found for type ImageModel!
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at

Exception in querying mongodb using spring boot

I am trying to query MongoDB with the following code. Though as per documentation it seems correct I am still getting runtime exception at the time of execution of the query. Please let me know if there is anything wrong.
#Repository
public interface UserRepository extends MongoRepository<User, String> {
#Query("{'mobileNumber': ?0, 'password': ?1 }")
User findByLogin(String mobileNumber, String password);
}
Exception:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.bson.json.JsonParseException: JSON reader was expecting ':' but found 'password'.] with root cause
org.bson.json.JsonParseException: JSON reader was expecting ':' but found 'password'.
at org.bson.json.JsonReader.readBsonType(JsonReader.java:132) ~[bson-3.6.3.jar!/:na]
at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:149) ~[bson-3.6.3.jar!/:na]
at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:45) ~[bson-3.6.3.jar!/:na]
at org.bson.Document.parse(Document.java:105) ~[bson-3.6.3.jar!/:na]
at org.bson.Document.parse(Document.java:90) ~[bson-3.6.3.jar!/:na]
at org.springframework.data.mongodb.core.query.BasicQuery.<init>(BasicQuery.java:67) ~[spring-data-mongodb-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
at org.springframework.data.mongodb.repository.query.StringBasedMongoQuery.createQuery(StringBasedMongoQuery.java:136) ~[spring-data-mongodb-2.0.6.RELEASE.jar!/:2.0.6.RELEASE]
at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(Abstra

Spring Cloud Config Zookeeper Exception

I am trying to use Spring cloud config with zookeeper for configuration management.
My build.gradle looks like:
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.cloud:spring-cloud-starter-zookeeper-config')
compile('org.springframework.cloud:spring-cloud-config-server')
}
Here is my bootstrap.properties file:
spring.application.name = myapp
spring.cloud.zookeeper.connectString: localhost:2181
This is the application class:
#SpringBootApplication
#EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
But the application fails to launch and gives an exception:
Error starting Tomcat context.
Exception: org.springframework.beans.factory.BeanCreationException.
Message: Error creating bean with name 'servletEndpointRegistrar'
defined in class path resource
[org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration.class]
: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException
: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]
: Factory method 'servletEndpointRegistrar' threw exception;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'healthEndpoint'
defined in class path
resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]
: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException
: Failed to instantiate [org.springframework.boot.actuate.health.HealthEndpoint]
: Factory method 'healthEndpoint' threw exception;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException
: Error creating bean with name 'configServerHealthIndicator'
defined in class path resource
[org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.class]
: Unsatisfied dependency expressed through
method 'configServerHealthIndicator' parameter 0;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException
: Error creating bean with name 'org.springframework.cloud.config.server.config.CompositeConfiguration'
: Unsatisfied dependency expressed through method 'setEnvironmentRepos' parameter 0;
nested exception is org.springframework.beans.factory.BeanCreationException
: Error creating bean with name
'defaultEnvironmentRepository' defined in class path
resource [org/springframework/cloud/config/server/config/DefaultRepositoryConfiguration.class]
: Bean instantiation via factory method failed;
nested exception is org.springframework.beans.BeanInstantiationException
: Failed to instantiate
[org.springframework.cloud.config.server.environment.MultipleJGitEnvironmentRepository]
: Factory method 'defaultEnvironmentRepository' threw exception;
nested exception is java.lang.NullPointerException
What could be the reason behind this? Seems like it is searching for git repository even after specifying zookeeper.

Error creating bean with name 'dao'

i dont know ahy i got this error when i wanna test my app using spring beans this the main test :
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext context=
new ClassPathXmlApplicationContext(new String[]
{"applicationContext.xml"});
IBanqueMetier metier=(IBanqueMetier) context.getBean("metier");
metier.addClient(new Client("C1", "AD1"));
metier.addClient(new Client("C2", "AD2"));
}
and this the 1rst error :
Exception in thread "main"org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dao': Injection of persistence dependencies
failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements: org.gestion.bp.entities.Compte.employe
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:342)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
With Spring exceptions, it's important that you read the whole message up to the very end. I usually split the message into several lines to make it more readable:
Exception in thread "main"org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dao': Injection of persistence dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]:
Invocation of init method failed;
nested exception is org.hibernate.AnnotationException:
Illegal attempt to map a non collection as a #OneToMany, #ManyToMany or #CollectionOfElements:
org.gestion.bp.entities.Compte.employe
As you can see, you made an error in the definition of the field org.gestion.bp.entities.Compte.employe