问题:
最近项目用到实体类id自增的情况,但是mongodb实现id自增需要手动配置
解决办法:
1、新建注解接口
package com.wasu.galaxy.dao.entity;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @program: wasutv-api
* @description: springboot-mongodb 自增注解
* @author: GP_Bao
* @create: 2020-03-09 15:50
**/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {
}
2、设置监听类,重载类里面的onBeforeConvert方法
package com.wasu.galaxy.dao.entity;
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;
import java.lang.reflect.Field;
/**
* @program: wasutv-api
* @description: 实现监听类
* @author: GP_Bao
* @create: 2020-03-09 15:54
**/
@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) {
logger.info(event.getSource().toString());
final Object source = event.getSource();
if (source != null) {
ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
ReflectionUtils.makeAccessible(field);
// 如果字段添加了我们自定义的AutoIncKey注解
if (field.isAnnotationPresent(AutoIncKey.class)) {
// 设置自增ID
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);
return inc.getIncId();
}
}
3、在需要的实体类属性中加上注解
@AutoIncKey
最后 就可以测试啦