我的Rest API遇到了問題。當我試圖在更新或保存方法之后進行findById或其他獲取操作時,我的JPA并沒有在API中更新這些資料,但在資料庫中這些資料卻被更新了。所以我是否可以在獲取資料之前或在向資料庫添加日期之后不使用用戶的flash和清除。因為我認為這不是正確的代碼。
protected ENTITY findById(Long id, Class<ENTITY> entityClass) {
try {
tx.begin();
entityManager.flush()。
entityManager.clear()。
final ENTITY entity = entityManager.find(entityClass, id);
tx.commit()。
if (entity == null) {
log.warning(entityClass.getSimpleName() " is null") 。
return null。
}
return entity。
} catch (final HibernateException ex) {
tx.rollback()。
throw new DaoException("Canot find entity by id", ex)。
}
這是我的更新方法
protected ENTITY update(entity entity) {
try {
tx.begin();
entityManager.merge(entity);
tx.commit()。
return entity。
} catch (final HibernateException ex) {
tx.rollback()。
throw new DaoException("Canot update entity", ex)。
}
uj5u.com熱心網友回復:
你需要使用entityManager.persist(),你將不需要再次使用flush/clear,因為物體管理器中的背景關系在.persist()之后被更新。
請看這里的解釋。JPA EntityManager: 為什么使用 persist() 而不是 merge()?
protected ENTITY findById(Long id, Class<ENTITY> entityClass) {
final ENTITY entity = entityManager.find(entityClass, id)。
...
}
protected ENTITY update(entity entity) {
...
entityManager.persist(entity)。
}
uj5u.com熱心網友回復:
看起來你漏掉了tx.begin();和tx.persist();用以下幾行替換你的try塊內的所有內容;
tx.begin()。?
entityManager.persist(entity)。
tx.commit()。
entityManager.close()。
return物體。
如果這還不能解決你的問題,請看一下我使用的這個模板。
/declare these variables at the top of the class and intialize them in the constructor.
private EntityManagerFactory emf;
private EntityManager em;
private EntityTransaction tx;
 。
public Constructor(){
emf = Persistence.createEntityManagerFactory("persistence_unit_name"/span>)。
em = emf.createEntityManager()。
}
 。
/Add object to database
public void addPerson (Object person){
 。
//應該在try-catch中。
tx = em.getTransaction();
tx.begin();
em.persist(person);
tx.commit()。
emf.close()。
em.close()。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317502.html
標籤:
上一篇:我怎樣才能在Windows10上使用真正的iPhoneiOS設備測驗我在Xamarin.Forms上編碼的ios應用程式?
