記錄下方法以及踩過(guò)的坑象踊,本文主要參考了https://blog.csdn.net/qq_16313365/article/details/72781469#commentBox莺奔,在此致謝鸠珠!
(1)首先定義序列實(shí)體類:
@Document(collection ="sequence")
public class SeqInfo {
? ??????//getter and setter
????????@Id
? ? ? ? private String id;
? ? ? ? @Field("collection_name")
????????private String collName;
? ? ? ? @Field("seq_id")
????????private Long seqId;
}
(2)接著定義注解AutoIncKey
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {
}
(3)定義監(jiān)聽(tīng)類SaveEventListener
注意:這里面有個(gè)坑。按照https://blog.csdn.net/qq_16313365/article/details/72781469#commentBox中作者的方法以及評(píng)論中@yaoyaoyue的方法會(huì)出現(xiàn)問(wèn)題:在下文insert的時(shí)候返回的結(jié)果顯示字段值自增了锌介,但是到數(shù)據(jù)庫(kù)中一看卻是初始值0嗜诀,也就是并沒(méi)有寫(xiě)入數(shù)據(jù)庫(kù)AbstractMongoEventListener中的方法void onBeforeConvert(BeforeConvertEvent event)才成功。
@Component
public class SaveEventListener extends AbstractMongoEventListener {
private final MongoTemplatemongoTemplate;
? ? @Autowired
? ? public SaveEventListener(MongoTemplate mongoTemplate) {
????????this.mongoTemplate = mongoTemplate;
? ? }
@Override
? ? public void onBeforeConvert(BeforeConvertEvent<Object>?event){
????????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)) {
????????????????????????// 設(shè)置自增ID
? ? ? ? ? ? ? ? ? ? ? ? field.set(source, getNextId(source.getClass().getSimpleName()));
? ? ? ? ? ? ? ? ? ? }
????????????????}
????????????});
? ? ? ? }
}
/**
* Description:獲取下一個(gè)自增ID
*
? ? * @param collName 集合名(這里用類名)
? ? * @return 序列值
? ? * @author example@gmail.com
? ? * @Date 2019/2/21 9:58
*/
? ? private LonggetNextId(String collName){
????????Query query =new Query(Criteria.where("collection_name").is(collName));
? ? ? ? Update update =new Update();
? ? ? ? update.inc("seqId", 1);
? ? ? ? FindAndModifyOptions options =new FindAndModifyOptions();
? ? ? ? options.upsert(true);
? ? ? ? options.returnNew(true);
? ? ? ? SeqInfo seqInfo =mongoTemplate.findAndModify(query, update, options, SeqInfo.class);
? ? ? ? assert seqInfo !=null;
? ? ? ? return seqInfo.getSeqId();
? ? }
}
(4)使用方法如下孔祸。本文才用的是MongoRepository方式對(duì)MongoDB進(jìn)行增刪查改隆敢,只需要insert即可,不需要其他代碼崔慧。
@Service
public class ApplicationService Implimplements ApplicationService {
? ? @Autowired
? ? private?ApplicationRepository?applicationRepository;
? ??@Override
????public Application create(Application application) {
? ? ? ? //其他代碼
? ? ? ? return applicationRepository.insert(application);
? ? }
這樣就可以了拂蝎。
最后說(shuō)一句,簡(jiǎn)書(shū)自帶的MarkDown模式真難用惶室,插入代碼塊后温自,一部分代碼還是顯示為文本玄货。請(qǐng)問(wèn)你們的技術(shù)是怎么搞得?