0

I followed this link to test multi-tenancy with JakartaEE 8, Payara web-server 5.2021.9, Hibernate 5.4.32 and MariaDb 10.5. When I persist and throw exception, my testing entity is not rollback(still persisted in database) even using entityManager.getTransaction().rollback() or setRollbackonly().

Here're my codes:

@Stateless 
public class TestRollBackBean extends Dao {

    @PostConstruct
    public void init() {
        logger.info("is initializing");
    }

    @PreDestroy
    public void detroy() {
        logger.info("is detroying");
    }

    private static final Logger logger = LogManager.getLogger();
 
    public void testCertFormTx(final String tenantId) {
        final EntityManager em = getEntityManager(tenantId);
        final EntityTransaction etx = em.getTransaction();
        final CertificateForm cf = new CertificateForm();//ntity
        try {
            logger.debug("test persist and rollback for CertificateForm");
            
            cf.setActive(true);
            cf.setDesp("testing"); 
            em.persist(cf); 
            logger.debug("new Id: {}", () -> cf.getId());
            throw new Exception("test rollback now");
        } catch (Exception e) { 
            etx.setRollbackOnly(); 
        } finally {
            if (em != null && em.isOpen()) { 
                em.close();
            }
        }
    }
}

What I'm wrong or missing?

PeterL355
  • 75
  • 1
  • 9
  • did you try with throwing the exception from the catch and using `@Transactional` in the method so that JPA can find that error is thrown and perform automatic rollback? – Saravanan Jan 27 '22 at 16:44
  • I ever tried with @TransactionAttribute(REQUIRED) in the method, but it did not rollback. If I use above codes without multi-tenancy, it can rollback(not persisted to database). – PeterL355 Feb 14 '22 at 11:21

0 Answers0