JPA: Modelling a Map<Entity, Entity> - jpa

I am running into an exception when generating the database tables with EclipseLink for the following model:
#Entity
#Table(name="RXRACTSPOT")
public class ActivitySpot implements Serializable,IsSerializable {
.....
#OneToMany
private Map<CustomAttributeDefinition, CustomAttributeRestriction> customAttributes;
--
#Entity
#Table(name="RXRCUSTATTRREST")
public class CustomAttributeRestriction implements Serializable
--
#Entity
#Table(name="RXRCUSTATTRDEF")
public class CustomAttributeDefinition implements Serializable
I encounter the following exception:
Exception in thread "main" javax.persistence.PersistenceException: Exception >[EclipseLink-0] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
Exception [EclipseLink-93] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The table [RXRCUSTATTRREST] is not present in this descriptor.
Descriptor: RelationalDescriptor(com.rubiconred.activitystream.core.model.ActivitySpot --> [DatabaseTable(RXRACTSPOT)])
Runtime Exceptions:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:417)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getServerSession(EntityManagerFactoryImpl.java:164)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:221)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:209)
at com.rubiconred.activitystream.database.ActivityStreamDatabaseUtils.dropAndCreateTables(ActivityStreamDatabaseUtils.java:64)
at com.rubiconred.soauiext.server.db.CreateOneSpotDatabases.main(CreateOneSpotDatabases.java:16)
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.IntegrityException
If I remove the Map in RXRACTSPOT then the tables RXRCUSTATTREST and RXRCUSTATTRDEF are successfully created. With the Map neither table is created and the exception is thrown. I suspect I am missing some annotation on the Map but I have been unable to find an example for a Map with both key and value as Entities.

Seems like a bug. Try the latest release, if it still occurs please log a bug.
You could also create another Entity class to represent the three way join table instead of using a Map.

Related

Axon extensions.mongo 4.3 in spring boot: noSuchMethodError - com.mongodb.MongoClient

i'm trying to run mvn clean install on a spring boot project with Axon's extensions.mongo dependency. The mongo database is up and running in a docker container
in the pom i have:
<dependency>
<groupId>org.axonframework.extensions.mongo</groupId>
<artifactId>axon-mongo</artifactId>
<version>4.3</version>
</dependency>
Then i have a #Configuration class which has - among others, these members:
#Value("${spring.data.mongodb.host:127.0.0.1}")
private String mongoHost;
#Value("${spring.data.mongodb.port:27017}")
private int mongoPort;
#Value("${spring.data.mongodb.database:user}")
private String mongoDatabase;
#Bean
public MongoClient mongoClient() {
var mongoFactory = new MongoFactory();
mongoFactory.setMongoAddresses(Collections.singletonList(new ServerAddress(mongoHost, mongoPort)));
return mongoFactory.createMongo();
}
Then when running mvn clean install i get this stack trace:
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoClient' defined in com.springbank.user.core.configuration.AxonConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NoSuchMethodError: 'com.mongodb.connection.ConnectionPoolSettings$Builder com.mongodb.connection.ConnectionPoolSettings$Builder.maxWaitQueueSize(int)'
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mongodb.MongoClient]: Factory method 'mongoClient' threw exception; nested exception is java.lang.NoSuchMethodError: 'com.mongodb.connection.ConnectionPoolSettings$Builder com.mongodb.connection.ConnectionPoolSettings$Builder.maxWaitQueueSize(int)'
Caused by: java.lang.NoSuchMethodError: 'com.mongodb.connection.ConnectionPoolSettings$Builder com.mongodb.connection.ConnectionPoolSettings$Builder.maxWaitQueueSize(int)'
Spring Boot will auto-configure the MongoClient when it is available on the classpath. You only need to specify the proper spring.mongo properties in your application.properties (which you already use judging by your configuration).
So the easy fix is to just remove this #Bean method.
If you really want to use that MongoFactory you will need to figure out which version of MongoDB (the Mongo Client in this case) is compatible with it.

Cglib proxy errors using and Spring Data when moving from Spring XD M5 to Release 1.0.0

We're moving a number of batch jobs from Spring XD M5 to the 1.0.0 release.
When creating and deploying the jobs, we are hitting an issue with cglib proxy functionality when autowiring Spring Data repositories (for Neo4J in this case).
The tail end of the stack trace:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'datasetRepository': Post-processing of FactoryBean's singleton object failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class
com.sun.proxy.$Proxy112]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy112
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:116)
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1512)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:313)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1017)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
... 54 more
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class [class com.sun.proxy.$Proxy112]: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final
class class com.sun.proxy.$Proxy112
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:212)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:494)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:379)
at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:339)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.postProcessObjectFromFactoryBean(AbstractAutowireCapableBeanFactory.java:1698)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:113)
... 61 more
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class com.sun.proxy.$Proxy112
at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33)
at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:57)
at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202)
... 68 more
The Spring Data repository interface is annotated with #Repository as follows:
#Repository
public interface DatasetRepository extends GraphRepository<Dataset>
{
public Dataset findOneById(String id);
public Dataset findOneByName(String name);
}
And the corresponding autowired attribute in our bean class which triggers the exception:
#Autowired
private DatasetRepository datasetRepo;
The bean itself is defined in our XD job XML as follows:
<bean id="myBean" class="com.mycompany.MyBean"/>
And the configuration bean (component scanned in the job cfg XML):
#Configuration
#EnableNeo4jRepositories({ "com.mycompany.repositories" })
public class CustomNeo4jConfiguration implements InitializingBean
The versions of Spring Data Neo4J which we deploy into the XD lib folder are as follows:
spring-data-neo4j : 3.2.0.RELEASE
spring-data-neo4j-rest : 3.2.0.RELEASE
The setup is all on a dev PC (for now) with XD running in distributed mode:
redis server
Zookeeper server (1x)
Oracle job repository (local XE instance for now)
1x admin and 1x container
Any help around configuration of the job, Spring Data repository or XD container would be much appreciated.
Thanks
Remove the #Repository annotation on your GraphRepository and you should be fine. Don't forget to enable component scanning.

Functional operators causes JPA to crash? (Bug?)

I'm having a very strange problem with JPA and Java 8 functional programming.
I have a Student and Presentation class and their relationship is bidirectional. Everything worked fine in Java 7, but I just switched to Java 8.
This works (visible is private, has no setters):
public static void setAllVisible(boolean visible) {
for (Presentation presentation : new PresentationRepository().findAll()) {
presentation.visible = visible;
}
}
This crashes:
public static void setAllVisible(boolean visible) {
new PresentationRepository().findAll().forEach(x -> x.visible = visible);
//same for new PresentationRepository().findAll().stream().forEach(x -> x.visible = visible);
}
Which gives this exception multiple times:
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader#4554617c
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [BachelorproefPU] failed.
Internal Exception: Exception [EclipseLink-7250] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.ValidationException
Exception Description: [class models.users.Student] uses a non-entity [class models.planning.Presentation] as target entity in the relationship attribute [field presentation].
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:127)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:107)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at persistence.JPAEntityManager.getEntityManagerFactory(JPAEntityManager.java:45)
at models.repositories.Repository.<init>(Repository.java:23)
at models.repositories.UserRepository.<init>(UserRepository.java:15)
at main.DbInitializer.<init>(DbInitializer.java:27)
at main.DbInitializer.main(DbInitializer.java:23)
I'm pretty sure the persistence.xml is configured correctly (because it works without Java 8) and all classes are included and have #Entity. It's also not the Student class, because if I comment that out, the error just gives another class.
What's causing this? Maybe it's also worth mentioning that I get a compile crash once a while and that they ask me to send the project to Oracle.
Think you'll find that current EclipseLink doesn't support Java 1.8 syntaxis; look at
https://github.com/averri/jpa-lambda-integration-test
I use DataNucleus v4.0 for my projects and works for Java 1.8

Creating table form JPA Entity fails

I have set-up a completely new JPA Project in Eclipse (Kepler)...after I ran into issues in an existing project.
I intend to write a JpaEntity and let Eclipse (or JPA respectively) create the respective table in the database but this fails and I can't figure out the reason.
Eclipse tells me Table "myentrances" cannot be resolved. Of course...it doesn't exist by now. ...it shall be created yet.
Here's my JpaEntity:
#Entity
#Table(name="myentrances")
#NamedQuery(name="MyEntrance.findAll", query="SELECT e FROM MyEntrance e")
#TableGenerator(name = "myentrances")
#Access(PROPERTY)
public class MyEntrance implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int entranceId;
#OneToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER, orphanRemoval = true)
#PrimaryKeyJoinColumn
private Address address;
#Column(nullable=false)
private double maxHeight;
#Column(nullable=false)
private String maxHeightUom;
private static final long serialVersionUID = 1L;
public MyEntrance() {
super();
}
public int getEntranceId() {
return this.entranceId;
}
public void setEntranceId(int entranceId) {
this.entranceId = entranceId;
}
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
public double getMaxHeight() {
return this.maxHeight;
}
public void setMaxHeight(double maxHeight) {
this.maxHeight = maxHeight;
}
public String getMaxHeightUom() {
return this.maxHeightUom;
}
public void setMaxHeightUom(String maxHeightUom) {
this.maxHeightUom = maxHeightUom;
}
}
Here's my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JpaTest" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.tsystems.ikt.model.Address</class>
<class>com.tsystems.ikt.model.MyEntrance</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.ddl-generation.output-mode" value="database"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/myDb"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
Here's the exception I get:
[EL Config]: metadata: The element [method getAddress] is being defaulted to a one to one mapping.
[EL Config]: metadata: The target entity (reference) class for the one to one mapping element [method getAddress] is being defaulted to: class com.tsystems.ikt.model.Address.
[EL Config]: metadata: The access type for the persistent class [class com.tsystems.ikt.model.Address] is set to [FIELD].
[EL Config]: metadata: The access type for the persistent class [class com.tsystems.ikt.model.MaiEntrance] is set to [FIELD].
[EL Config]: metadata: The alias name for the entity class [class com.tsystems.ikt.model.MyEntrance] is being defaulted to: MyEntrance.
[EL Config]: metadata: The column name for element [getEntranceId] is being defaulted to: ENTRANCEID.
[EL Config]: metadata: The column name for element [getMaxHeightUom] is being defaulted to: MAXHEIGHTUOM.
[EL Config]: metadata: The column name for element [getMaxHeight] is being defaulted to: MAXHEIGHT.
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: org.eclipse.persistence.dynamic.DynamicClassLoader#580760d7
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [JpaTest] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.tsystems.ikt.model.MyEntrance] has no primary key specified. It should define either an #Id, #EmbeddedId or an #IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:127)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:107)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:177)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.buildEntityManagerFactory(Main.java:94)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.execute(Main.java:80)
at org.eclipse.jpt.jpa.eclipselink.core.ddlgen.Main.main(Main.java:68)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [JpaTest] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.tsystems.ikt.model.MyEntrance] has no primary key specified. It should define either an #Id, #EmbeddedId or an #IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1954)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1945)
at org.eclipse.persistence.internal.jpa.deployment.JPAInitializer.callPredeploy(JPAInitializer.java:98)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:96)
... 5 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [JpaTest] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.tsystems.ikt.model.MyEntrance] has no primary key specified. It should define either an #Id, #EmbeddedId or an #IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:230)
... 9 more
Caused by: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.tsystems.ikt.model.MyEntrance] has no primary key specified. It should define either an #Id, #EmbeddedId or an #IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
at org.eclipse.persistence.exceptions.ValidationException.noPrimaryKeyAnnotationsFound(ValidationException.java:1422)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor.validatePrimaryKey(EntityAccessor.java:1536)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor.processMappingAccessors(EntityAccessor.java:1243)
at org.eclipse.persistence.internal.jpa.metadata.accessors.classes.EntityAccessor.process(EntityAccessor.java:697)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processStage2(MetadataProject.java:1793)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.processORMMetadata(MetadataProcessor.java:576)
at org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:585)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1869)
... 7 more
I am only using field access (in Address as well).
I am using Eclipselink 2.5.1.
By the way:
Isn't it possible to create a table for just a single newly created JpaEntity? Do I ever have to chose MyProject-->JPA Tools-->Generate TableS from EntitieS? This seems to create ALL existing tables as well, does it? What if I have already created a bunch of tables and now just want to add one further table based by a newly created JpaEntity?
The default access mode for entities in JPA is AccessType.FIELD.
You have overwritten it by declaring #Access(PROPERTY) for the entity therefore #Id annotation is unnoticed by the persistence provider while processing metadata. Try to remove #Access(PROPERTY) annotation to solve the problem.
What if I have already created a bunch of tables and now just want to
add one further table based by a newly created JpaEntity?
It depends from a scenario:
if dropping existing tables is forbidden for any reason (i.e. in case of legacy database): leave create-tables in persistence.xml so that the provider creates the table based on a new entity (i.e. MyEnterance); for already existing table you may use DROP TABLE myentrances later on to remove the corresponding table and recreate it automatically during the next start up - the provider will take care of recreating the entity from scratch
if dropping existing tables is allowed: replace create-tables with drop-and-create-tables in persistence.xml - the provider will take care of recreating the whole entity model from scratch

Spring data jpa: No property flush found for type void

I am using Spring Data JPA to develop a Spring MVC app. I built a JPA repository.
public interface AccessReportRepository extends JpaRepository<AccessReport, Long> {
}
I also use Spring Data Mongo along with JPA in my project.
When I run the project, I get this error.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lastDateController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.innolabmm.software.mongotest.springrest.ReadingService com.innolabmm.software.mongotest.springrest.LastDateController.readingService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'readingService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.innolabmm.software.mongotest.springrest.AccessReportRepository com.innolabmm.software.mongotest.springrest.ReadingService.reportRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accessReportRepository': FactoryBean threw exception on object creation; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property flush found for type void
Does anyone have an idea what is going on? I am ready to provide more information if this will help solve the problem. Thanks in advance.
Are you using Spring Boot?
I had the same exception thrown when trying to use JPA and Mongo together, in a Spring Boot application. I found that the Repositories were always being interpreted by both JPA and Mongo, leading to problems as my repositories specifically extend JpaRepository.
I only wanted JPA repositories generated, so added the following to the Application entry point.
#EnableAutoConfiguration(exclude={MongoRepositoriesAutoConfiguration.class})
If you are using MongoDB with JPA (my JPA db is mysql) do this:
create separete packages for domain objects and for repositories (DAOs): i.e. demo.mysql.domain, demo.mysql.dao, demo.mongo.domain, demo.mongo.dao
in your configuration class use these annotations:
#EntityScan(basePackages={"demo.mysql.domain"})
#EnableJpaRepositories(basePackages={"demo.mysql.dao"})
#EnableMongoRepositories(basePackages={"demo.mongo.dao"})
annotate your JPA entities with #Entity and put them all in demo.mysql.domain package
annotate your MongoDB entities with #Document and put them all in demo.mongo.domain package
keep all of MongoDB reporitories in demo.mongo.dao package
keep all JPA repositories in demo.mysql.dao package
all mongo repositories should extend MongoRepository (i.e. public interface TransactionRepository extends MongoRepository)
all JPA repositories should extend JpaRepository (i.e. public interface CityRepository extends JpaRepository)
This is by far the easiest and the cleanest way that I have found (after digging through docs, btw.) to have MongoDB and Mysql working in one Spring Boot app.
That is what I have tried and what works. You could probably use MongoTemplate or extend CrudRepository instead of JpaRepository, or whatever else, try it, it might work.