java mongodb orm implementation-ORM based on mongodb-driver

Keywords: Java Netty Redis

Introduction:
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.

m-db

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

Instructions

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
*
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface CompoundIndexed {

  Indexed[] value();

  int order() default -1;

  boolean unique() default true;
}

/**
* Normal Index: Index a field
*/
@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
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})
@Retention(RetentionPolicy.RUNTIME)
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)
    @BsonProperty("build_id")
    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.setY(6);
        buildPo.setX(7);
        buildPo.setUid(1);
        buildPo.setName("Beijing SOHO Large building");
        buildPo.setType("High-end buildings");
        MongoManager.getInstance().add(buildPo);
    }
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();
            po.setUid(2049);
            po.setX(i);
            po.setY(i);
            list.add(po);
        }
        MongoManager.getInstance().addMany(list);
    }

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));
       System.out.println(b.getBuildId());
   }

   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");
        MongoManager.getInstance().update(b);
    }

[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). ( https://github.com/twjitm/m-db-test/blob/main/images/update.jpg?raw=true )]

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("127.0.0.1:27017", true);
    }

3.2 Asynchronous Operating Principles

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

Last

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.

Author: twjitm@gmail.com

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