本文介绍了JpaRepository、@Transaction 和 repository.saveAndFlush的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我第一次尝试使用服务/存储库方法,但遇到了一个问题.基本上我想在我的服务中做的是持久化我的实体,然后在同一个服务方法中使用它的 ID.

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.

最初我打算使用 @GeneratedValue 和 Sequences 但放弃并决定手动刷新实体并获取 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.

My Repository 是一个使用 Spring Data 的接口,因此它支持手动刷新.据我了解,它也用@Transactional 进行了注释.我的 Service 方法也是用@Transactional 注释的.

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.

我发现实体仅在 Service 方法返回时才保留,即使我在保存实体后立即刷新(或使用 saveAndFlush).我认为刷新会强制数据库更改?

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?

推荐答案

Spring-data-jpa 在调用 save 时返回未来"实体(即带有 id),因此:

Spring-data-jpa return the "future" entity (i.e. with id) when you call save, so:

Foo foo = new Foo();
foo = this.fooRepository.save(foo); // also work on Collections
this.fooRepository.flush();
// use foo.getId();

这篇关于JpaRepository、@Transaction 和 repository.saveAndFlush的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 11:50