hibernate rollback not working in service layer

511 Views Asked by At

i have issue in rollback insert/update data in postgresql database, in service layer, where as in DAO layer it is working fine.

My DAO junit test Code

@ContextConfiguration("classpath:datasource-context-test.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class SellerDAOTest {
@Test
    @Rollback(true)
    public void testAddSeller() {
        try {
            SellerDO sellerDO = getSellerDO();
            sellerDAOImpl.addSeller(sellerDO);
        } catch (DataException cdExp) {
            Assert.fail();
        }

    }
}

and my dao impl looks like

@Override
@Transactional(propagation = Propagation.REQUIRED)
public void addSeller(SellerDO sellerDO) throws DataException {
    try {
        Session session = this.getSessionFactory().getCurrentSession();
        session.save(sellerDO);
    } catch (HibernateException hExp) {
        throw new DataException("DB Error while adding new seller details", hExp);
    }

}

and above test rollbacks the data inserted after executing the test. but i problem is in my service layer. rollback is not happening in here

@ContextConfiguration({ "classpath:datasource-context-test.xml", "classpath:service-context-test.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
@Component
public class SellerTest {
    @Junit
    @Rollback(true)
    public void testAddSeller() {

        SellerBO sellerBO = getSellerBO();
        try {
            manageSellerServiceImpl.addSeller(sellerBO);
        } catch (ServiceException csExp) {
            Assert.fail();
        }

    }
}

my service code

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void addSeller(SellerBO sellerBO) throws ServiceException {
      sellerDAOImpl.addSeller(sellerDO);
}

i dont know why it is not working in service layer. i have tried couple of solution stackoverflow, but none worked. help needed

1

There are 1 best solutions below

0
On BEST ANSWER

Using REQUIRES_NEW will run your code in a new transaction separately from the one that JUnit creates. So you are creating a nested transaction by invoking your service layer code.

Change Propagation.REQUIRES_NEW to Propagation.REQUIRED in your service layer. Also since Propagation.REQUIRED is the default propagation level, you can remove this annotation.