package com.example.seq.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "sequence")
public class SequenceId {
@Id
private String id;
private long seq;
//get, set, toString...
}
SequenceDao.java
package com.example.seq.dao;
import com.example.seq.exception.SequenceException;
public interface SequenceDao {
long getNextSequenceId(String key) throws SequenceException;
}
SequenceDaoImpl.java
package com.example.seq.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoOperations;
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.Repository;
import com.example.seq.exception.SequenceException;
import com.example.seq.model.SequenceId;
@Repository
public class SequenceDaoImpl implements SequenceDao {
@Autowired
private MongoOperations mongoOperation;
@Override
public long getNextSequenceId(String key) throws SequenceException {
//get sequence id
Query query = new Query(Criteria.where("_id").is(key));
//increase sequence id by 1
Update update = new Update();
update.inc("seq", 1);
//return new increased id
FindAndModifyOptions options = new FindAndModifyOptions();
options.returnNew(true);
//this is the magic happened.
SequenceId seqId =
mongoOperation.findAndModify(query, update, options, SequenceId.class);
//if no id, throws SequenceException
//optional, just a way to tell user when the sequence id is failed to generate.
if (seqId == null) {
throw new SequenceException("Unable to get sequence id for key : " + key);
}
return seqId.getSeq();
}
}
SequenceException.java
package com.example.seq.exception;
public class SequenceException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String errCode;
private String errMsg;
//get, set...
public SequenceException(String errMsg) {
this.errMsg = errMsg;
}
}