javamongodbspring-bootoptimistic-locking

Spring Boot MongoDB the field with version annotation does not increment


This question asked several times before, but the answers in these questions didn't work for me.

This is my Book document

@Document
@NoArgsConstructor
@ToString
@Getter
@Setter
@EqualsAndHashCode
public class Book
{
    @Id
    private String id;
    @Indexed
    private String name;
    private Double price;
    private Integer stock;
    @Version
    private Integer version;

    public Book(String name, Integer stock, Double price)
    {
        this.name = name;
        this.stock = stock;
        this.price = price;
    }
}

This is my bookRepository implementation

public interface BookRepository extends MongoRepository<Book, String>
{
}

And this is my customBookRepository implementation

@Repository
public class CustomBookRepository
{
    private final BookRepository bookRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    public CustomBookRepository(BookRepository bookRepository)
    {
        this.bookRepository = bookRepository;
    }

    public Book save(Book book)
    {
        return bookRepository.save(book);
    }

    public Optional<Book> findById(String id)
    {
        return bookRepository.findById(id);
    }

    public boolean updateQuantity(Integer stock, String id)
    {
        BasicDBObject query = new BasicDBObject();
        query.put("_id", new ObjectId(id)); // (1)

        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("stock", stock); // (2)

        BasicDBObject updateObject = new BasicDBObject();
        updateObject.put("$set", newDocument); // (3)

        final UpdateResult book = mongoTemplate.getCollection("book").updateOne(query, updateObject);
        return book.wasAcknowledged();
    }
}

The version does not change, it stays 0 at my every update on the entities. (for inst. updateQuantity())

I've tried adding annotation @EnableMongoAuditing

@SpringBootApplication
@EnableMongoAuditing
public class ReadingIsGoodApplication
{

    public static void main(String[] args)
    {
        SpringApplication.run(ReadingIsGoodApplication.class, args);
    }
}

It doesn't change anything.


Solution

  • Don't use a "custom repository"

    Use jpa methods to save/update. Then the version field will be updated.