Issue
Problem Description.
So I have an item that I want to use with MongoDB
@Value.Immutable
@Gson.TypeAdapters
@Criteria.Repository
interface Person {
@Criteria.Id
String id();
String fullName();
}
And in-order to support pojos, I've created a MongoClient with the following settings:
CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.codecRegistry(codecRegistry)
.build();
However, whenever I try to perform an insert operation, I receive an error whereas bson can't find the codec for the Immutable class.
The code that creates the problem:
MongoCollection<Person> people = db.getCollection("peoples", Person.class).withCodecRegistry(pojoCodecRegistry);
Person person = ImmutablePerson.builder()
.id("1")
.fullName("person")
.build();
InsertOneResult result = people.insertOne(shahar);
And the error:
Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class with.immutables.ImmutablePerson.
I've tried registering a ClassModel to CodecRegistry for ImmutablePerson as shown below
.register(ClassModel.builder(ImmutablePerson.class).enableDiscriminator(true).build())
However, it saves the "instance" instead of the data in it
Question
What needs to be changed so that the simple insert operation works? Is it possible to do it with immutables?
Solution
I've reached a solution that works:
@Value.Immutable
@Criteria
@Criteria.Repository
@JsonSerialize(as = ImmutableUser.class)
@JsonDeserialize(as = ImmutableUser.class)
public interface User {
@Criteria.Id
ObjectId _id();
String firstName();
String lastName();
UserNameAndPassword userNameAndPassword();
}
By setting the above annotations, imported from "jackson-core" and immutables "criteria-common", when compiling the code a corresponding repository was created, In this case - "UserRepository", which then can be used to perform CRUD operations.
Example for adding a user:
UserRepository users = new UserRepository(mongoManager.getBackend());
users.insert(user); // add
users.users.find(UserCriteria...); // read
users.update(user); // update
users.delete(UserCriteria...); // delete
I recommend reading on immutables-Criteria, additionally, I've used the examples provided in the following repository immutables-git-repo, under criteria->mongo.
Answered By - Shahar Azar
Answer Checked By - Gilberto Lyons (JavaFixing Admin)