简体   繁体   中英

using flush and clear after each persist or merge

Well, i have a trigger function in postgreSQL that generate a number each time a new row is inserted. But JPA/Hibernate don't show this generated number, after a "entityManager.persist(bean)". So i did the following to force it:

@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
    public AbstractBean save(AbstractBean bean) {
        try {
            logger.info("Salvando Bean " + bean.getClass().getName());
            entityManager.persist(bean);
            entityManager.flush();
            entityManager.clear();
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Ocorreu um erro ao tentar salvar. MSG ORIGINAL: "
                    + e.getMessage());
            throw new DAOException("Ocorreu um erro ao tentar salvar");
        }
    }

I inserted the "flush and clear" after persist method and everything is fine. But my big doubt is: My method "save" is called for all application to save any JavaBean, so if i make flush and clear in all persist or merge don't have problem ? This is the better choice ?

In my opinion it is not optimal to have flush and clear for all saves - what is the purpose of a cache in this situation.

I would implement

em.getEntityManagerFactory().getCache().evict(theSpecialClass, thePrimaryKey);

for where bean instanceOf theSpecialClass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM