Spring Boot mongo审计@version问题

我刚开始一个新项目,想使用 Sprint Boot 2.1,一开始就遇到了问题。我想做的是使用 Spring Boot Mongo 来管理数据库。我想要一个带有@Version注释的乐观锁。但是,我发现它似乎@Version会影响save()MongoRepository 中的行为,这意味着 dup key 错误。


以下是示例代码。


POJO


    @Data

    @AllArgsConstructor

    @NoArgsConstructor

    @Document

    public class Person {


        @Id public ObjectId id;

        @CreatedDate public LocalDateTime createOn;

        @LastModifiedDate public LocalDateTime modifiedOn;

        @Version public long version;

        private String name;

        private String email;


        public Person(String name, String email) {

            this.name = name;

            this.email = email;

        }


       @Override

        public String toString() {

            return String.format("Person [id=%s, name=%s, email=%s, createdOn=%s, modifiedOn=%s, version=%s]", id, name, email, createOn, modifiedOn, version);

        }

    }

MongoConfig


    @Configuration

    @EnableMongoRepositories("com.project.server.repo")

    @EnableMongoAuditing

    public class MongoConfig {


    }

存储库


    public interface PersonRepo extends MongoRepository<Person, ObjectId> {

        Person save(Person person);

        Person findByName(String name);

        Person findByEmail(String email);

        long count();

        @Override

        void delete(Person person);

    }

如Official Doc 中所示,我的version字段位于 中long,但 dup 键错误发生在 second save,这意味着它insert再次尝试,即使对象中的 id 也是如此。

我也尝试了Longinversion字段,它没有发生 dup 键并按预期保存为更新,但createdOn成为null第一个save(这意味着insert)


控制器


Person joe = new Person("Joe", "aa@aa.aa");

System.out.println(joe.toString());

this.personRepo.save(joe);

Person who = this.personRepo.findByName("Joe");

System.out.println(who.toString());

who.setEmail("bb@bb.bb");

this.personRepo.save(who);

Person who1 = this.personRepo.findByName("Joe");

Person who2 = this.personRepo.findByEmail("bb@bb.bb");

System.out.println(who1.toString());

System.out.println(who2.toString());


据我所知,spring 使用 id 存在作为保存行为控制,这意味着如果 id 存在,那么保存就像 mongo 的插入一样。但是,在这里,版本似乎也会影响保存行为或影响spring识别id存在的方式。


问题:如何将 MongoAudit 与 MongoRepository 一起使用?我犯了任何错误/错误吗?


手掌心
浏览 280回答 2
2回答

UYOU

对于使用@Version,您必须首先从数据库中检索数据模型,并且在更新数据后,您必须将相同的数据保存到数据库中。例如:&nbsp; personRepo.findByName(name).ifPresent(person-> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; person.setEmail("email@gamil.com");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; personRepo.save(person);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.info("Updated Data: {}", person);&nbsp; &nbsp; &nbsp; &nbsp; });@CreatedDatenull如果您没有将其添加@Version到您的模型类中,将永远如此。它适用于@Version如果您没有添加@Version到模型类并且您尝试使用具有模型类来更新相同的模型类@Version,那么这里还要添加一点,它会再次给您重复 id 错误。

牛魔王的故事

我仍然无法弄清楚问题所在。但是,即使我的设置与上面的帖子完全相同,由于我将 Spring Boot 从 2.1.0 升级到 2.1.1,现在一切正常(无论我使用什么类型的版本,Long/long)以下是我现在正在使用的库版本。spring-boot-starter-data-mongodb:2.1.1.RELEASE:&nbsp; -> spring-data-mongo:2.1.3.RELEASE&nbsp; -> mongodb-driver:3.8.2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java