java mongodb orm implementation-ORM based on mongodb-driver

Keywords: Java Netty Redis

MongoDB is a very promising database, and MongoDB officially locates itself as a generic database, which is somewhat like MySQL. Although its popularity is far from the level of MySQL, there is one possible inappropriate comparison. Like MySQL N years ago, MongoDB will become stronger and more popular over time.

Due to the complexity and inconvenience of business development based on mongo's official api, this project is encapsulated based on the official api, which simplifies the query, creation and index maintenance of documents.


English Simplified Chinese

brief introduction

What is this?

Welcome to this project.

This project is based on mongodb-driver encapsulation development, greatly simplifying the native API, allowing developers to focus on the business itself. The project uses annotation style patterns to simplify configurations like xml.

major function

1: Simple Document Mapping
2: Embedded Document Mapping
3: Asynchronous storage. Batch Storage
4: Index Management

major functionSupported or notIs it asynchronous
Read operationyesno
Write operationyesyes
Batch Readyesno
Batch Writingyesyes
Index Maintenanceyesno


Index Management

1. Index Maintenance

Simplify the use and maintenance of mongodb indexes by annotating @Indexed and @CompoundIndexed for automatic creation and maintenance of simple and combined indexes

* Joint index: Multiple field combination index composition
public @interface CompoundIndexed {

  Indexed[] value();

  int order() default -1;

  boolean unique() default true;

* Normal Index: Index a field
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD})
public @interface Indexed {

  boolean unique() default false;

  String name();

  int order() default -1;

* Failure Time Index: This document is time-sensitive
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD})
public @interface ExpireIndex {

  boolean unique() default false;

  String name() default "";

  int order() default -1;

For detailed use, see IndexTest, when an index is tagged on each document's po class or field, the index is created.

2. Use of simple documents

Simple Document: Document structure is simple, field type is basic data type field.
Steps to use:

2.1: Assembling entity class PO objects
 * A simple document
@MongoDocument(table = "user_build")
@CompoundIndexed(value = {@Indexed(name = "uid"), @Indexed(name = "build_id")})
public class BuildPo extends AbstractMongoPo {

    @MongoId(name = "uid")
    private long uid;
    @MongoId(name = "build_id", tick = true)
    private long buildId;
    private int x;
    private int y;
    private String type;
    private String name; 

It specifies the table name by annotating the @MongoDocument database name, and the @CompoundIndex annotation specifies which fields to use as the union index
You can also use @Indexed to specify an index individually and @MongoId to specify a primary key. Since mongodb cannot achieve a mysql-like auto-growth, the index uses this comment to specify whether or not a primary key auto-growth occurs.

2.2 Add data
  public static void addBuild() throws MException {
        BuildPo buildPo = new BuildPo();
        buildPo.setName("Beijing SOHO Large building");
        buildPo.setType("High-end buildings");
2.3 Bulk Add
    private static void addManyBuild() throws MException {
        List<BuildPo> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            BuildPo po = new BuildPo();

For example, the added data can be queried in mongodb

2.4 Query

There are two ways to query, one by using the primary key of the @mongoID annotation and the other by using a field to find the query

    * Primary Key Query
   public static void get() throws MException {
       BuildPo b = MongoManager.getInstance().get(BuildPo.class, PrimaryKey.builder("uid", 1), PrimaryKey.builder("build_id", 7));

   public static void getAll() throws MException {
       List<BuildPo> bs = MongoManager.getInstance().getAll(BuildPo.class, PrimaryKey.builder("uid", 1));
       System.out.println("getAll size=" + bs.size());

 public static void findOne() throws MException {
       BuildPo b = MongoManager.getInstance().findOne(BuildPo.class, Query.builder().and("uid", 1).and("build_id", 7));
       System.out.println(b.getX() + "|" + b.getY());


   public static void findAll() throws MException {
       List<BuildPo> bs = MongoManager.getInstance().findAll(BuildPo.class, Query.builder().and("uid", 1).and("y", 6), QueryOptions.builder().limit(100));
       System.out.println("findAll size=" + bs.size());

2.5 Modification

Modify a field in a document by, for example, modifying the build name of the query

    public static void update() throws MException {
        BuildPo b = MongoManager.getInstance().get(BuildPo.class, PrimaryKey.builder("uid", 1), PrimaryKey.builder("build_id", 2));
        b.setName("new name build");

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-qB7M58hV-1638093207578). ( )]

3. Asynchronous: Writing

The system supports asynchronous operation. The operation is encapsulated as a task and added to an asynchronous queue, where the database execution thread gets the operation task from the queue.

3.1 Turn on asynchronous operation

 private static void init() {
        mongoManager = new MongoManager("", true);

3.2 Asynchronous Operating Principles

 private void execute() {
        if (pool.isEmpty()) {
        pool.forEach((k, v) -> collectionManager.getCollection(k).bulkWrite(v));


Source Address

Thank you for your support for this project. If you find something bad, please submit issues. Welcome to star 🌟🌟🌟🌟. If you have any questions, you can contact me and discuss them together.


Posted by shlomikalfa on Sun, 28 Nov 2021 16:00:56 -0800