简体   繁体   中英

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 ?

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.

try using as shown below :

@Override
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void upsert(String lastSuccessfullRun) {
        for( tableData in Tables){
         insertIntoDB(tableData);
       }
    }



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

if you use "propagation=Propagation.REQUIRES_NEW" in insertIntoDB method then it will create a new transaction and commit it when insertIntoDB method completed .

@Transactional only works when you call the method throw proxy so in your case it doesn't work. If you really want that your changes reflected in Database and in your PersistenceContext that associated with your active transaction you can use

EntityManager.flush();

But keep it in mind when using flush() the changes to the data are reflected in database after encountering flush, but it is still in transaction and can be rollback and the transaction is still active but when you use commit() the changes are made into the database & transaction also ends there.

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