Spring boot mongodb auditing error
I solved this issue with the next configuration:
@Configuration@EnableMongoRepositories(basePackages = "YOUR.PACKAGE")@EnableMongoAuditingpublic class MongoConfig extends AbstractMongoConfiguration { @Value("${spring.data.mongodb.host}") private String host; @Value("${spring.data.mongodb.port}") private Integer port; @Value("${spring.data.mongodb.database}") private String database; @Override public MongoClient mongoClient() { return new MongoClient(host, port); } @Override protected String getDatabaseName() { return database; } @Bean public MongoTemplate mongoTemplate() throws Exception { return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()); } @Bean public MongoDbFactory mongoDbFactory() { return new SimpleMongoDbFactory(mongoClient(), database); }}
just add the bean for MongoTemplate
with the constructor of MongoTemplate(MongoDbFactory mongoDbFactory, @Nullable MongoConverter mongoConverter)
Quoting from JIRA ticket
You need to pipe the MappingMongoConverter that's available in the environment into MongoTemplate as well, i.e. use new MongoTemplate(dbFactory, converter). The constructor you use is for convenience, one-off usages. We usually recommend to use AbstractMongoConfiguration in case you'd like to customize anything MongoDB specific as this makes sure the components are wired together correctly.
More specifically, you need to inject pre-configured MappingMongoConverter or if you need to use your own converter, at least use pre-configured MongoMappingContext.
I had this problem also with spring boot 2.2I had both @EnableMongoRepositories
and @EnableMongoAuditing
as configuration and i got the error Couldn't find PersistentEntity for type class
the problem in my case was the structure of the packages: Application class was a level lower than part of my model that used auditing.
I found on many forum posts that the 2 annotations are not compatible together in spring 2.2, but after restructuring the packages I was able to use both with success in spring boot 2.2