自己实现mongo ORM

引入依赖:

<-- mongo -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.12.11</version>
</dependency>
<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.4</version>
</dependency>

编写domain:

@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
@Collection(name = "user", comment = "用户表")
public class User {
    @Id
    String userId;
    @Col(value = "phone")
    String phone;
    @Col(value = "password")
    String password;
    @Col(value = "salt")
    String salt;
    @Col(value = "state")
    int state;
    @Col(value = "name")
    private String name;
    @Col(value = "rechargeGold")
    int rechargeGold;
    @Col(value = "onlineTime")
    private Date onlineTime;
    @Col(value = "offlineTime")
    private Date offlineTime;
    @Col(value = "createTime")
    private Date createTime;
    @Col(value = "modifyTime")
    private Date modifyTime;

}
/**
 * mongodb字段映射
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Col {
    String value();
}
/**
 * mongodb集合
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Collection {
    /**
     * @return name属性表示实体所对应表的名称,默认表名为实体的名称。
     */
    String name() default  "";

    /**
     * @return comment集合名字
     */
    String comment() default "";
}
/**
 * 标识ID
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Id {
}

下面实现mongoTemplate:

@Component
public class MongoTemplate {
    @Value("mongo.db.dataBase")
    private String db;
    @Autowired
    private MongoClient mongoClient;

    private static final Map<String, Map<String, Field>> CLASS_NAME_FIELD_MAP = new HashMap<>();
    private static final String ID = "_id";

    /**
     * 插入数据
     * @param obj
     * @param type
     */
    public void insert(Object obj, Class<?> type) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(db);
        String className = type.getName();
        Map<String, Field> fieldMap = CLASS_NAME_FIELD_MAP.getOrDefault(type.getName(), loadClassInfo(type));
        Collection tableAnnotation = type.getAnnotation(Collection.class);
        if (Objects.isNull(tableAnnotation)) {
            throw new RuntimeException("Collection配置异常");
        }
        String tableName = tableAnnotation.name();
        if (tableName.isEmpty()) {
            tableName = className;
        }
        MongoCollection<Document> table = mongoDatabase.getCollection(tableName);
        Document document = fillDocument(obj, fieldMap);
        table.insertOne(document);
        try {
            fieldMap.get(ID).set(obj, document.getObjectId(ID).toString());
        } catch (IllegalAccessException e) {
            throw new RuntimeException("获取ID异常", e);
        }
    }

    /**
     * 充填document
     * @param obj
     * @param fieldMap
     * @return
     */
    private Document fillDocument(Object obj,Map<String, Field> fieldMap){
        Document document = new Document();
        for (Field field : fieldMap.values()) {
            try {
                Object value = field.get(obj);
                if (Objects.isNull(value)) {
                    continue;
                }
                String fieldName = field.getName();
                Id id = field.getAnnotation(Id.class);
                if (Objects.nonNull(id)) {
                    field.set(obj, value);
                    document.put(ID, value);
                } else {
                    Col colInfo = field.getAnnotation(Col.class);
                    if (Objects.nonNull(colInfo)) {
                        document.put(colInfo.value(), value);
                    } else {
                        document.put(fieldName, value);
                    }
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException("构造参数异常", e);

            }
        }
        return document;
    }
    /**
     * 加载类信息
     *
     * @param type
     * @return
     */
    private Map<String, Field> loadClassInfo(Class<?> type) {
        Map<String, Field> result = new HashMap<>();
        Arrays.stream(type.getDeclaredFields()).peek(a -> a.setAccessible(true)).forEach(a -> {
            if (Objects.nonNull(a.getAnnotation(Id.class))) {
                result.put(ID, a);

            } else {
                result.put(a.getName(), a);
            }
        });
        CLASS_NAME_FIELD_MAP.put(type.getName(), result);
        return result;
    }
}

后面的慢慢更新..

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值