Implementation of java mongodb orm - ORM based on mongodb driver (II: connection maintenance and primary key self increment)

Posted by djs1 on Sat, 25 Dec 2021 11:56:11 +0100

introduction:
MongoDB is a very promising database. The official positioning of MongoDB is a general database. In fact, this positioning is somewhat similar to MySQL. Although its popularity is far from reaching the level of MySQL, the author may make an inappropriate comparison. MongoDB, like MySQL N years ago, will become more and more powerful and popular over time.

As mentioned in the previous article, it is developed through the mongodb driver native package to encapsulate easy-to-use interfaces, reduce the use threshold and remove redundant code. Make the project more concise

1, : connection maintenance (encoding / decoding)
2, Ticket user defined - self incrementing primary key:

1: Connection maintenance (encoding / decoding)

1.1 maintenance of connecting client s

  private final Map<String, MongoCollection<Document>> collections = new ConcurrentHashMap<>();
    public MongoCollection<Document> getCollection(String database, String collection) {
        String key = this.getDbKey(database, collection);
        MongoCollection<Document> db = collections.get(key);
        if (db == null) {
            MongoDatabase dbs = mongoClient.getDatabase(database);
            db = dbs.withCodecRegistry(DEFAULT_CODEC_REGISTRY).getCollection(collection);
            collections.put(key, db);
        }
        return db;
    }

When obtaining a connection, check whether there is such a Collection. If yes, query and return it directly through the corresponding key. If not, create a MongoDatabase through mongoclient. When mongodb creates a connection, it needs to register an encoder and decoder, that is, what we often call an encoder and decoder.

1.2: encoder and decoder
mongodb can convert stored bson into pojo entity in java. A given encoder and decoder are required. In the connection pipeline, we need to give the following codeProvider. PojoCodecProvider provides codecs for registered POJOs through ClassModel abstraction.

CodecProvider[] array = new CodecProvider[]{
            new ValueCodecProvider(),
            new DBRefCodecProvider(),
            new DocumentCodecProvider(new DocumentToDBRefTransformer()),
            new DBObjectCodecProvider(),
            new BsonValueCodecProvider(),
            new GeoJsonCodecProvider(),
            PojoCodecProvider.builder().automatic(true).build(),
    };

Create a Builder through the Builder method, so that the CodecProvider of final type can be created. When automatic is set to true, it means that when querying through any class, the system will create a classmodelcodecProvider for this class. Otherwise, you need to register a specific class manually.

2, Ticket user defined - self incrementing primary key:

2.1 primary key in mongodb
In MongoDB_ The id field is the primary key of the collection so that each document can be uniquely identified in the collection_ The id field contains a unique ObjectID value. By default, when you insert a document into a collection, if you do not add a field name with_ id, MongoDB will automatically add an Object id field
In the project m-db, we rewrite the mongodb primary key through a self adding function.

In mongodb, there is no primary key auto increment function. We need to manually implement one. Coincidentally, mongodb has a self increment insertion operation such as $inc. use this method. Encapsulate a self incrementing tag annotation, which makes it convenient for the primary key to be self incremented.


For example, in userinfo, uid is a self incrementing field, so you only need to mark mongoId on uid. Then tick is true

2.2 primary key auto increment principle

As mentioned earlier, the $inc operation of mongodb can realize field self increment. Inspired by this, create a table like tickeid with the following structure, where key represents an entity, that is, a combination of table name and field name, and value is the self increment value. Therefore, it is only necessary to detect whether the self increment function is marked on the current field when adding data. If so, Realize self increment.

@MongoDocument(table = "mdb_tick")
public class TickId extends AbstractMongoPo {

    @Indexed(unique = true, name = "key")
    @MongoId(name = "key", root = true)
    private String key;
    private long value;
}

The implementation principle is as follows. Build a document with the architecture of {key:tablename,$inc:{value:1}}, and then return the increased value.

    private synchronized long _nextId(String name) {
        Document document = new Document();
        document.put("key", name);
        Document up = new Document();
        up.put("$inc", new Document("value", 1));
        MongoCollection<Document> collection = mongoCollectionManager.getCollection(TickId.class);
        Document result = collection.findOneAndUpdate(document, up);
        if (result == null) {
            document.put("value", 1);
            collection.insertOne(document);
            return 1;
        }
        return result.getInteger("value");
    }

Topics: Java Database MongoDB