我有延長BaseRepository多個倉庫如下:更新查詢提交
public abstract class IsoRepository<T extends Serializable> {
@PersistenceContext
protected EntityManager entityManager;
public void persist(T obj) {
entityManager.persist(obj);
}
}
@Stateless
public class T1Repository extends BaseRepository<T1> {
// methods depending on repository
}
@Stateless
public class T2Repository extends BaseRepository<T2> {
public Optional<T2> findByOrderId(String id) {
return entityManager.createNamedQuery(/* ... */, T2.class)
.setParameter("id", id).getResultList().stream().findFirst();
}
}
// and others
EJB bean包含方法承擔一切節約交易:
@Stateless
public class TransactionService {
@EJB
private T2Repository t2Repository;
public void saveTransaction() {
// Here occurs logic that saves new entities to database via repositories injected with EJB annotation
// and also as the last operation update is performed:
T2 t2 = t2Repository.findById(id);
t2.setProperty(someProperty);
t2Repository.persist(t2);
}
}
的問題是,所有插入查詢是保存在數據庫中,但不是這一個糟糕的更新。我發現我需要明確地調用entityManager.flush()
,因爲它似乎解決了這個問題,但我不明白爲什麼會發生這種情況。我一直認爲在事務提交後,所有數據都會自動刷新。我有沒有改變配置中的東西?
平齊()是在一個事務結束自動調用。你在一個事務中調用了t2Repository,並且你沒有自動刷新。 「我一直認爲,交易完成後,所有數據都會自動刷新」 - 你是對的。 – xyz
但是不應該在方法'saveTransaction'完成後調用flush?因爲現在看起來好像不是(手動調用方法中的最後一個操作) – Fuv
pls顯示persistence.xml文件以及如何配置事務 – xyz