0

I try simple CRUD in Spring Boot with Mongodb. I have problem with id number. How can I auto increment id. I tried but couldn't do it

Is there any simple auto increment way?

Controller

@Autowired
EmployeeRepo repo;

@RequestMapping(value = "home", method = RequestMethod.GET)
public String getHomePage(Model model) {

    Employee employee = new Employee();

    employee.setId(1);
    employee.setName("deniz");
    employee.setPassword("123");

    repo.save(employee);  

    ...

Employee

@Document(collection = "Employee")
public class Employee {

@Id
private long id;

private String name;
private String password; 

// getter and setter
DnzDmr
  • 83
  • 2
  • 8
  • Did you see this ? https://stackoverflow.com/a/8384133/641627 – alexbt Nov 15 '18 at 19:18
  • @alexbt That's right. Problem solved when I tried ObjectId instead of Long. Because the collections in "_id" are unique. No need for auto increment. Thanks for comment and sorry for my bad english :) – DnzDmr Nov 15 '18 at 21:05

1 Answers1

0
  public long getNextSequenceId(String key) {

    Query query = new Query(Criteria.where("_id").is(key));

        Update update = new Update();
    update.inc("seq", 1);

    FindAndModifyOptions options = new FindAndModifyOptions();
    options.returnNew(true);

    SequenceId seqId = 
            mongoOperation.findAndModify(query, update, options, SequenceId.class);

    return seqId.getSeq();

  } 
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83