Search code examples
javaspringentitymanagerpropagation

Spring EntityManager Commit Transaction as method completes


I am using spring EntityManager and have a requirement to commit records on method completion. That is i have two methods for ex ::

    @Override
    @Transactional
    public void upsert(String lastSuccessfullRun) {
        for( tableData in Tables){
         insertIntoDB(tableData);
       }
    }

and the method insertIntoDB contains the buisness logic which actually does the update queries

    @Override
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void insertIntoDB (String tableData) {
        em.persist(tableData)
    }

But the problem is that the method doesn't commit as it returns for the next loop in upsert method.

How can i commit on method completion ?


Solution

  • Check the documentation.

    Method visibility and @Transactional

    When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

    Even if your method is public, you're calling it in another method in the same class, so you are not going trugh the proxy and the @Transactional(propagation=Propagation.REQUIRES_NEW) on insertIntoDB method has no effect.

    So try it in AspectJ mode, as in the docs.