java JpaRepository、@Transaction 和 repository.saveAndFlush
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12122489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JpaRepository, @Transaction, and repository.saveAndFlush
提问by Nick Spacek
I'm taking my first crack at the Service/Repository approach and am running into an issue. Essentially what I want to do in my Service is persist my entity and then use its ID in the same Service method.
我第一次尝试使用服务/存储库方法,但遇到了一个问题。基本上我想在我的服务中做的是持久化我的实体,然后在同一个服务方法中使用它的 ID。
Originally I was going to use @GeneratedValue and Sequences but gave up and settled on manually flushing the entity and grabbing the ID , which I thought would be easier.
最初我打算使用 @GeneratedValue 和 Sequences 但放弃并决定手动刷新实体并获取 ID ,我认为这会更容易。
My Repository is an Interface using Spring Data, so it has support for manual flushes. As I understand it, it also is annotated with @Transactional. My Service method is also annotated with @Transactional.
我的 Repository 是一个使用 Spring Data 的接口,因此它支持手动刷新。据我了解,它也用@Transactional 进行了注释。我的服务方法也用@Transactional 注释。
What I've found is that the entity is only persisted upon return of the Service method, even when I flush immediately after saving the entity (or use saveAndFlush). I thought that flushing would force the DB changes?
我发现该实体仅在 Service 方法返回时才保留,即使我在保存实体后立即刷新(或使用 saveAndFlush)。我认为刷新会强制数据库更改?
回答by
Spring-data-jpa return the "future" entity (i.e. with id) when you call save, so:
当您调用 save 时,Spring-data-jpa 返回“未来”实体(即带有 id),因此:
Foo foo = new Foo();
foo = this.fooRepository.save(foo); // also work on Collections
this.fooRepository.flush();
// use foo.getId();
回答by user2787412
call saveAndFlush method will work!
调用 saveAndFlush 方法会起作用!
Foo foo = new Foo();
foo = this.fooRepository.saveAndFlush(foo);
// use foo.getId();