用注解实现mongodb主键自增

最近比较清闲,所以分享一个很早之前使用mongodb时候,需要主键自增时的处理方式。

又因为现在Java的注解很火,所以就拿这个功能为例吧。

说到Java注解,可能一些小白觉得很难,但是其实并非如此。

首先,我们先创建一个注解,

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {

}

当然,因为是创建的注解,所以我们需要创建一个保存所有自增集合主键值的地方。

import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "IncInfo")
public class IncInfo {

    private String id;// 主键
    private String collName;// 需要自增id的集合名称
    private Integer incId;// 当前自增id值


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCollName() {
        return collName;
    }

    public void setCollName(String collName) {
        this.collName = collName;
    }

    public Integer getIncId() {
        return incId;
    }

    public void setIncId(Integer incId) {
        this.incId = incId;
    }
}

下面创建一个监听器,继承 AbstractMongoEventListener<Object> ,重写其中的onBeforeConvert方法来处理自增功能。

其实写到这里,如果会写注解的人应该已经知道该怎么写了。

那么就直接上代码!

import java.lang.reflect.Field;
import com.yaxin.show.mongodb.AutoIncKey;
import com.yaxin.show.mongodb.IncInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

@Component
public class SaveEventListener extends AbstractMongoEventListener<Object>{

    private static final Logger logger= LoggerFactory.getLogger(SaveEventListener.class);

    @Autowired
    private MongoTemplate mongo;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        final Object source = event.getSource();
        if (source != null) {
            ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    ReflectionUtils.makeAccessible(field);
                    // 如果字段添加了我们自定义的AutoIncKey注解
                    if (field.isAnnotationPresent(AutoIncKey.class)) {
                        // 设置自增ID
//                        System.out.println("--------------------=------------------=------------------:"+source.getClass().getSimpleName());
                        field.set(source, getNextId(source.getClass().getSimpleName()));
                    }
                }
            });
        }
    }

    private Integer getNextId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        update.inc("incId", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        IncInfo inc= mongo.findAndModify(query, update, options, IncInfo.class);
//        System.out.println("--------------------=------------------=----------- inc.getIncId();-------:"+ inc.getIncId());
        return inc.getIncId();
    }


}

现在功能是写好了,如何使用呢

@Document(collection="FileConfigureLinks")
public class FileConfLinksVo implements Serializable {

	@Id
	@AutoIncKey
	private int id;

	private String name;

	private int source;

	private int target;

	private String lineStyle;

	private String label;

	private int processType;

}

把咱们创建的AutoIncKey注解加到需要的字段上面即可。

private MongoTemplate mongoTemplate;

@RequestMapping(value="/showBootUpOther",method = RequestMethod.GET, produces ={"application/json;charset=UTF-8"})
public Result showBootUpOther(@RequestParam(value = "name", required = false) String name){
    FileConfLinksVo fileConfLinksVo = new FileConfLinksVo();
    this.mongoTemplate.insert(fileConfLinksVo);
}

然后调用一下上面的借口,测试一下吧。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章