java - JPA2.0 commits transaction on flush immediatly -


i'm using ejb3 , jpa2 in project containing several modules. lately have noticed db-records won't rollback on exception. after doing research found entity manager commits transaction on flush immediatly before method ends, can't rollback on exception.

i inject entity manager using

@persistencecontext private entitymanager entitymanager; 

to create new record persist , flush beeing called in same class

entitymanager.persist(entity); entitymanager.flush(); 

even if call throw new runtimexception("") right after flush, wont rollback. on debug after flush invoked can select db-record database tool, before method ends.

i checked persistence.xml , found nothing unusual. dont use other specifig configuration. i'm out of ideas might cause behavior. appriciate clue.

you need specify transaction boundaries, otherwise new transaction opened , commited after each data manipulation query (insert, update, delete). em.flush() trigger such sql query executed, open implicit transaction , commit if sql successful, rollback in case of error.

in order set transaction boundaries , make runtimeexception trigger rollback, best option call entitymanager methods ejb object. must use jta datasource, not resource_local. if don't use jta datasource, need manage transactions yourself, ie. using entitymanager.gettransaction() object.

outside of ejb, or non-jta datasource, not have transaction open, unless start calling entitymanager.gettransaction().begin(). however, in way, transaction not rolled when exception thrown. instead, must roll in catch block. outside of java ee container, in java se application. in java ee, suggest use jta datasource. example:

public class notanejb {   public persistentity(entitymanager em, myentity entity) {     em.gettransaction().begin();     try {       em.persist(entity);       em.flush();       if (shouldfail()) {         throw new runtimeexception();       }       em.commit();     } catch (exception e) {       em.rollback();     }   } } 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -