MongoTemplate如何实现自增id
解决方法:
1.生成I自增id的工具类
import com.thinkcc.survet.base.domian.SequenceId;
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.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
@Component
public class GeneratedValue {
@Autowired
MongoTemplate template;
public Long getNextId(String collName) {
return query(collName);
}
private long query(String collName){
collName=collName.toLowerCase();
Query query = new Query(Criteria.where("id").is(collName));
Update update = new Update();
update.inc("next_id", 1);
FindAndModifyOptions options = new FindAndModifyOptions();
options.returnNew(true);
options.upsert(true);
SequenceId seqId = template.findAndModify(query, update, options, SequenceId.class,collName+".next_id");
return seqId.getNext_id();
}
}
2.用法
spring的bean直接注入上面的工具bean,例如
@Autowired
GeneratedValue generatedValue;
generatedValue.getNextId("collectionName");