I make a class like this
@BsonDiscrimintor
public class User {
@BsonId
private Integer _id;
// some properties
// getter & setter
}
and register to codec
ClassModel<User> userModel = ClassModel.builder(User.class).enableDiscriminator(true).build();
PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().register(userModel).build();
pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(), fromProviders(pojoCodecProvider));
mongoClient = new MongoClient("localhost", MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
mongoDatabase = mongoClient.getDatabase("bbs").withCodecRegistry(pojoCodecRegistry);
When I try to insert
public int addOne(User user) {
try {
user.set_id(Db.getNextId("user"));
userCollection.insertOne(user);
} catch (Exception e) {
e.printStackTrace();
}
return user.get_id();
}
But When I find it in mongo, its _id field type is ObjectID but not Int32. But I declared _id as Integer, Why?
The default type of id
in MongoDB is ObjectID
. It could be changed as you create table. It's not decided by the class define in java.
Actually, MongoDB would implicitly convert int
to ObjectID
when your code run.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.