我有一種情況,其中我Foo包含一個物件Bar,如果該Bar物件在 中不存在BarRepository,我想先將其持久化,然后繼續保存該Foo物件(首次創建 Foo 物件時不需要這樣做,但是出于某種原因,在使用新的 Bar 物件更新它時需要這樣做)。
我想知道將an EntityManager(更新)和Spring Repository(檢查是否存在)結合在一起時是否被認為是不好的做法或任何重大的性能問題。
這是我的特殊情況:
@Service
@AllArgsConstructor
public class FooService {
private final FooRepository fooRepository;
private final BarRepository barRepository;
private final EntityManagerFactory entityManagerFactory;
// works fine
public Foo update(long id, Consumer<Foo> consumer) {
var foo = get(id);
updateFields(foo, consumer);
var entityManager = entityManagerFactory.createEntityManager();
var transaction = entityManager.getTransaction();
transaction.begin();
if (foo.getBar() != null) {
if (!barRepository.existsById(foo.getBar().getId())) {// option 1
entityManager.persist(foo.getBar());
}
}
var update = entityManager.merge(foo);
transaction.commit();
entityManager.close();
return update;
}
// doesnt work yet, but the idea is this
public Foo update(long id, Consumer<Foo> consumer) {
var foo = get(id);
updateFields(foo, consumer);
var entityManager = entityManagerFactory.createEntityManager();
var transaction = entityManager.getTransaction();
transaction.begin();
if (foo.getBar() != null) {
var barId = foo.getBar().getId();
if (entityManager // option 2
.createNativeQuery(
"SELECT b FROM bar b WHERE b.text = ?1 AND b.duration = ?2")
.setParameter(1, barId.getText()())
.setParameter(2, barId.getDuration())
.getSingleResult()
== null) {
entityManager.persist(foo.getBar());
}
}
var update = entityManager.merge(foo);
transaction.commit();
entityManager.close();
return update;
}
}
在這兩種方法中,對我來說,第一種對我來說更干凈,因為與Foo另一種相比,物體的檢查很小,一個襯里,但我想遵循任何標準。
uj5u.com熱心網友回復:
Spring Data JPA 建立在 JPA 之上并在EntityManager內部使用。Spring Data 從來沒有打算從你的代碼庫中完全洗掉 JPA。它的目標是使簡單的東西變得瑣碎和舒適,同時在您需要直接使用它時不會妨礙您。
因此,EntityManager對于許多非平凡的應用程式來說,使用它是完全可以的,并且實際上是預期的。
但是訪問EntityManager生命的代碼與使用存盤庫的代碼在不同的抽象層上。因此,我建議將您的EntityManager使用代碼移動到您的存盤庫的自定義方法中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/484564.html
下一篇:SpringData-如果MyClass包含另一個Map<@Embeddable,@Embeddable>,是否可以使用@ElementCollection持久化Map<String
