Spring Boot MongoDB的版本注释字段不增加



这个问题以前问过好几次了,但是这些问题的答案都不适合我。

这是我的Book文档

@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;
}
}

这是我的bookRepository实现

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

这是我的customBookRepository实现

@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();
}
}

版本没有改变,它在每次更新实体时保持0。(for inst. updateQuantity())

我已经尝试添加注释@EnableMongoAuditing

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

它不会改变任何东西。

不要使用"自定义存储库">

使用jpa方法保存/更新。然后版本字段将被更新。

最新更新