代码之家  ›  专栏  ›  技术社区  ›  cblanto7

在mongo文档中创建自动递增字段

  •  0
  • cblanto7  · 技术社区  · 8 年前

    在我的Spring Boot应用程序中,我使用的是Spring Data MongoDB,我有一个简单的POJO代表用户:

    @EqualsAndHashCode
    public class User implements Storable {
    
      @Id
      public ObjectId id;
    
      @Getter @Setter public String firstName;
      @Getter @Setter public String lastName;
      @Getter @Setter public long userNum;
      @DBRef(lazy = true)
      @Getter @Setter public List<Section> sections = new ArrayList<Section>();
    
    ... 
    rest of class omitted
    ...
    
    }
    

    我的UserController看起来像这样:

    @Controller
    public class UserController {
    
      @Autowired
      UserRepository repository;
    
      @ModelAttribute("allSections")
      public List<Section> getSections() {
        return sectionRepository.findAll();
      }
    
      @RequestMapping(value = "/users/new", method = RequestMethod.POST)
      public String newUser(@ModelAttribute("user") User user) {
        User newUser = new User();
        newUser.userNum = user.userNum;
        newUser.firstName = user.firstName;
        newUser.lastName = user.lastName;
        newUser.sections = user.sections;
        newUser = repository.save(newUser);
    
        for (Section section : newUser.sections) {
          section.addToUsers(newUser);
          sectionRepository.save(section);
        }
    
        return "redirect:/users";
      }
    ... rest of controller omitted 
    }
    

    请注意,我想要自动生成的字段不是ID字段。

    我想要 userNum 属性将自动递增,以便在数据库中创建和存储的第一个用户对象以某个值开始。。。比如说9000,之后创建的每个用户增加1。

    我有什么选择?我看到过使用JPA的@GeneratedValue的例子,还有一些依赖自定义Mongo查询来创建序列集合的例子,但我都没能做到。。。

    2 回复  |  直到 8 年前
        1
  •  0
  •   Kamil Noster    8 年前

    创建计数器集合:

    public class Counter {
    
        @Id
        private String id;
    
        private long seq;
    
        public Counter(String id, long seq) {
            this.id = id;
            this.seq = seq;
        }
    
        // Getters and setters
    }
    

    然后是MongoRepository:

    @Repository
    public interface CounterRepository extends MongoRepository<Counter, String> {}
    

    @Service
    public class CounterServiceImpl implements CounterService {
    
        @Autowired
        private CounterRepository counterRepository;
    
        @Override
        public long getNext(String sequenceId) {
            Counter counter = counterRepository.findOne(sequenceId);
            long id = counter.getSeq();
            counter.setSeq(id + 1);
            counterRepository.save(counter);
            return id;
        }
    }
    
        2
  •  0
  •   cblanto7    8 年前

    好的,我已经弄明白了这是我如何实现的:

    类,它是一个简单的POJO

    public class UserNum {
    
      @Id
      private ObjectId id;
    
      @Getter
      @Setter
      public long seq;
    
      public UserNum(long seq) {
        this.seq = seq;
      }
    
    }
    

    UserNumRepository定义了一个方法,返回保存到集合中的最后一个UserNum

    @Repository
    public interface UserNumRepository extends MongoRepository<UserNum, String> {
      UserNum findTopByOrderByIdDesc();
    }
    

    UserNumService只需查找序列中的最后一个数字并创建下一个数字,然后保存并返回该数字。UserNumService是具有一个方法签名的接口。这将创建已创建和使用的所有usernum的集合。

    @Service
    public class UserNumServiceImpl implements UserNumService {
    
      @Autowired
      private UserNumRepository userNumRepository;
    
      @Override
      public long getNext() {
        UserNum last = userNumRepository.findTopByOrderByIdDesc();
        long lastNum = last.seq;
        UserNum next = new UserNum(lastNum + 1);
        userNumRepository.save(next);
        return next.seq;
      }
    }
    

    内部应用程序。java您可以使用起始编号或从mongo shell为集合种子。

    @Autowired UserNumRepository userNumRepository;
    
    public void run(String... args) throws Exception {
    
        userNumRepository.deleteAll();
        // start the sequence at 9000
        userNumRepository.save(new UserNum(9000)); 
    }
    

    最后,当需要发出新的userNum时,您可以简单地使用该服务,可能是在构造函数内部。