Issue
In Mongo 3.6, the following code worked to connect to a database using automatic POJO mapping:
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
mongoClient = new MongoClient("localhost",
MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
In Mongo 4.2, the classes have change slightly. Importantly, the create()
method of the new MongoClients class doesn't support the "localhost"
String parameter that the old constructor did. This means that the example provided in the Quick Start - POJOs section of the documentation (https://mongodb.github.io/mongo-java-driver/4.0/driver/getting-started/quick-start-pojo/) doesn't work.
33 CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
34 fromProviders(PojoCodecProvider.builder().automatic(true).build()));
35
36 MongoClientSettings settings = MongoClientSettings.builder()
37 .codecRegistry(pojoCodecRegistry)
38 .build();
39
40 mongoClient = MongoClients.create(settings);
I'm running this on Tomcat 9 and getting the following exception:
java.lang.IllegalArgumentException: hosts can not be null
com.mongodb.assertions.Assertions.notNull(Assertions.java:37)
com.mongodb.connection.ClusterSettings.<init>(ClusterSettings.java:446)
com.mongodb.connection.ClusterSettings.<init>(ClusterSettings.java:43)
com.mongodb.connection.ClusterSettings$Builder.build(ClusterSettings.java:260)
com.mongodb.MongoClientSettings.<init>(MongoClientSettings.java:733)
com.mongodb.MongoClientSettings.<init>(MongoClientSettings.java:59)
com.mongodb.MongoClientSettings$Builder.build(MongoClientSettings.java:481)
com.ossltd.whm.MongoDB.<init>(MongoDB.java:38)
...
This is a single instance of MongoDB running on the same server as Tomcat. How do I set the host value for this connection? Or is there something else I should do to get the same type of connection as the first example?
Solution
The problem was caused by conflicting jars being included in the war file.
I only found this by accident when trying to compare my pom.xml to an older working project. I mistakenly thought I was using the 3.6.0 jar files in this new project, but the Maven dependencies in Eclipse and using mvn dependency:tree
were only showing the 4.0.4 jar files.
When I checked the actual content of the war file (and in the /WEB-INF/lib directory of my installed webapp), I found that it contained the Mongo 3.6.0 jars, the 4.0.4 legacy jar and the 4.0.4 sync jar files. I couldn't find any references in my current project that would cause them to be included, although I had tried them previously.
The solution was to simply ensure that my build goal included clean
before the tomcat7:redeploy
.
It seems that the war file was being updated rather than re-created with the tomcat7:redeploy
goal.
Answered By - Spuggiehawk
Answer Checked By - Pedro (JavaFixing Volunteer)