今年的第一篇文章,首先祝大家新年快乐🎈🎈🎈然后前段时间在做项目的时候用mongodb来做数据库,遇到了一些问题,就是主键没法像mysql一样那么方便的自增,于是在网络上找了一些方法,并增加了一条判断
1.首先我们需要先加一个注解:
将@AutoIncKey注解添加到需要自增的实体类的id上
2.创建一个注解类: AutoIncKey.class
/**
*自定义的注解类
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {}
3.创建一个序列信息类: SeqInfo.class
/**
* 序列信息类
*/
@Data
public class SeqInfo {
String id;
String collName;
Integer value;
}
4.最后附上修改后的工具类代码: SaveEventListener.class
/**
* 监听添加操作,并将自增id插入
*/
@Component
public class SaveEventListener<T> 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());
T source = (T) 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
try {
// 判断添加了自增注解的当前对象的id是否未空,不为空时不自动生成id
if (source.getClass().getDeclaredField(field.getName())==null){
field.set(source, getNextId(source.getClass().getSimpleName()));
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
});
}
}
private String getNextId(String collName) {
Query query = new Query(Criteria.where("collName").is(collName));
Update update = new Update();
update.inc("value", 1);
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
SeqInfo seqInfo = mongo.findAndModify(query, update, options, SeqInfo.class);
return seqInfo.getValue() + ""; //可以根据需求拼接自己的格式
}
}
这样就可以直接愉快的使用自增主键了,本篇代码来源与9个月前…历史悠久,最近刚想起来这个问题,感谢关注,最近会持续更新,之前项目一直在忙,感谢关注.
如有问题,欢迎留言指出,谢谢