简体   繁体   中英

jpa flush or find before persist

In Spring declarative transactions management, when you trying to persist some entity which already exists in database, you are getting DataIntegrityViolationException only during Spring transaction commits. Therefore this method wouldn't work, exception in catch braces wouldn't caught here:

@Repository
public class UserDAOImpl implements UserDAO {

    @PersistenceContext
    EntityManager em;

    @Override
        public void createUserRole(String role) throws RoleAlreadyExistsException {
            try {
                UserRole userRole = new UserRole(role);
                em.persist(userRole);
            } catch (Exception e) {
                throw new RoleAlreadyExistsException();
            }
        }
}

only in the end of:

@Service("userService")
public class UserService 
    @Transactional
        public void createUserRole(String role) throws RoleAlreadyExistsException {
            userDao.createUserRole(role);
        }
}

I found out few options to resolve it:

  • not use @Transaction
  • use Flush
  • catch exception when invoke service
  • look up before persist

And now I considering between em.flush and em.find (before persist). Which method would be better to use(flush - losing performance, find - redundant request to database)? Also if i mistake somewhere here please point me.

Sometimes, flush may be useful to persist the data in between the ongoing transaction & then finally commit the changes afterwards. So you can also rollback the previous changes if there occurs some problem afterwards, like for batch insert/update.

So, when you call em.flush() , queries for inserting/updating/deleting associated entities are executed in the database. Any constraint failures (column width, data types, foreign key) will be known at this time.

In your case I will use flush.

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