Home > Back-end >  Why my data is not updated without flash and clear JPA
Why my data is not updated without flash and clear JPA

Time:09-17

I have problem with my Rest API. When I try to do findById or other fetch operations after some update or save methods, my JPA do not update this data in API but in database this data is updated. So can I dont user flash and clear before fetching or after adding date to DB. Because I think its not right code.

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.warn(entityClass.getSimpleName()   " is null");
                return null;
            }

            return entity;

        } catch (final HibernateException ex) {
            tx.rollback();
            throw new DaoException("Cannot find entity by id", ex);
        }
    }

This is my update method

    protected ENTITY update(ENTITY entity) {
        try {
            tx.begin();

            entityManager.merge(entity);

            tx.commit();

            return entity;

        } catch (final HibernateException ex) {
            tx.rollback();
            throw new DaoException("Cannot update entity", ex);
        }
    }

CodePudding user response:

You need to use entityManager.persist() and you will not need to use flush/clear again because the context in the entityManager is updated after .persist().

Please see the explanation here: JPA EntityManager: Why use persist() over merge()?

protected ENTITY findById(Long id, Class<ENTITY> entityClass) {
    
        final ENTITY entity = entityManager.find(entityClass, id);
        ...
}

protected ENTITY update(ENTITY entity) {

        ...
        entityManager.persist(entity);


}

CodePudding user response:

Looks like you left out tx.begin(); and tx.persist(); Replace everything inside your try block with the following lines;

tx.begin();
                
entityManager.persist(entity);
tx.commit();
entityManager.close();
return entity;

If this does not solve your problem than have a look at this template that I have used.

//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");
em  = emf.createEntityManager();
}
 
 
//Add object to database
public void addPerson (Object person){
 
//should be in try-catch
tx = em.getTransaction();
tx.begin();
em.persist(person);
tx.commit();
emf.close();
em.close();
}
  • Related