1import org.springframework.beans.factory.annotation.Autowired;
2import org.springframework.data.mongodb.core.FindAndModifyOptions;
3import org.springframework.data.mongodb.core.MongoTemplate;
4import org.springframework.data.mongodb.core.query.Criteria;
5import org.springframework.data.mongodb.core.query.Query;
6import org.springframework.data.mongodb.core.query.Update;
7import org.springframework.stereotype.Service;
8import sample.data.mongo.models.IdGenerator;
9import sample.data.mongo.repository.IdGeneratorRepository;
10
11@Service
12public class IdGeneratorService {
13
14 @Autowired
15 private IdGeneratorRepository idGeneratorRepository;
16
17 @Autowired
18 private MongoTemplate mongoTemplate;
19
20 public long generateId(String key) {
21
22 Query query = new Query();
23 // key = identified_by_Id;
24 Criteria criteria = new Criteria("identifier").is(key);
25 query.addCriteria(criteria);
26
27 Update update = new Update();
28 update.inc("counter", 1);
29
30 FindAndModifyOptions options = new FindAndModifyOptions();
31 options.upsert(true);
32 options.returnNew(true);
33
34 IdGenerator idGenerator = mongoTemplate
35 .findAndModify(query, update, options, IdGenerator.class);
36
37 return idGenerator.getCounter();
38 }
39}