How can we create Auto generated field for mongodb using spring boot

后端 未结 1 2095
无人及你
无人及你 2020-12-02 15:58

I write some code.I want to make questionId field in BaseQuestion Class as Autogenerated.Any solution for that? I am not using jpa jar.so i can\'t use @G

相关标签:
1条回答
  • 2020-12-02 16:45

    MongoDB came with all sophisticated ObjectId generation feature, but often you just jumped the ship from relational database, and you still want an easy to read / communicate numeric identifier field which automatically increments every time new record is inserted.

    One neat suggestion from MongoDB tutorial is to use a counter collection with a ‘counter name’ as its id, and a ‘seq’ field to store the last used number.

    When developing using Spring Data MongoDB, this neat trick can be written as a simple service. Here I used the collection name as the counter name so it’s easy to guess / remember.

    import static org.springframework.data.mongodb.core.FindAndModifyOptions.options;
    import static org.springframework.data.mongodb.core.query.Criteria.where;
    import static org.springframework.data.mongodb.core.query.Query.query;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.mongodb.core.MongoOperations;
    import org.springframework.data.mongodb.core.query.Update;
    import org.springframework.stereotype.Service;
    
    import com.model.CustomSequences;
    
    
    @Service
    public class NextSequenceService {
        @Autowired private MongoOperations mongo;
    
        public int getNextSequence(String seqName)
        {
            CustomSequences counter = mongo.findAndModify(
                query(where("_id").is(seqName)),
                new Update().inc("seq",1),
                options().returnNew(true).upsert(true),
                CustomSequences.class);
            return counter.getSeq();
        }
    }
    

    CustomSequences is just a simple class representing the collection. Please beware the usage of int data type, this will limit to 2^31 entries maximum.

    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document(collection = "customSequences")
    public class CustomSequences {
        @Id
        private String id;
        private int seq;
    
    // getters and setters
    }
    

    Then when inserting a new entry (with help of Spring MongoDB Repository support), just set the id field like this before you save it

    BaseQuestion baseQuestion = new BaseQuestion();
    baseQuestion.setQuestionId(nextSequenceService.getNextSequence("customSequences"));
    /* Rest all values */
    
    baseQuestionRepository.save(baseQuestion);
    

    If you don't like this way then you need to use MongoDBEvents and use onBeforeConvert to generate automated value using same above approach.

    Also above approach is threadsafe as findAndModify() is a thread safe atomic method

    0 讨论(0)
提交回复
热议问题