用註解實現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);
}

然後調用一下上面的藉口,測試一下吧。

 

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