All files
AutoIncKey.java | A customized Annotation to indicate the primary key is automatically increased |
SeqInfo.java | A document to save the updated key |
SaveEventListener.java | Mongo Event Listener |
AutoIncKey.java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {
}
SeqInfo.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SeqInfo {
@Id
private String id;// 主键
@Field
private String collName;// 集合名称
@Field
private Long seqId;// 序列值
}
SaveEventListener.java
/**
* 监听器用于监听Mongo Event,
* 该类继承AbstractMongoEventListener类,
* 因为我们需要在JAVA对象转换成数据库对象的时候操作id字段实现id自增,
* 所以覆盖onBeforeConvert方法
*/
@Component
public class SaveEventListener extends AbstractMongoEventListener<Object> {
@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(){
@Override
public void doWith(Field field)throws IllegalArgumentException,
IllegalAccessException {
ReflectionUtils.makeAccessible(field);
// 如果字段添加了我们自定义的AutoIncKey注解
if (field.isAnnotationPresent(AutoIncKey.class)) {
// 设置自增ID
field.set(source, getNextAutoId(source.getClass().getSimpleName()));
}
}
});
}
}
/**
* 获取下一个自增ID
*
* @param collName
* 集合(这里用类名,就唯一性来说最好还是存放长类名)名称
* @return 序列值
*/
private Long getNextAutoId(String collName) {
Query query = new Query(Criteria.where("collName").is(collName));
Update update = new Update();
update.inc("seqId", 1);
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
SeqInfo seq = mongo.findAndModify(query, update, options, SeqInfo.class);
assert seq != null;
return seq.getSeqId();
}
}