is there a way to force a transactional rollback without encountering an exception?

后端 未结 8 1981
鱼传尺愫
鱼传尺愫 2020-12-13 00:34

I have a method that does a bunch of things; amongst them doing a number of inserts and updates. It\'s declared thusly...

@Transactional(propagation = Propag         


        
8条回答
  •  死守一世寂寞
    2020-12-13 00:44

    Call setRollbackOnly() on the SessionContext if you're in an EJB.

    You can inject SessionContext like so:

    public MyClass {
        @Resource
        private SessionContext sessionContext;
    
        @Transactional(propagation = Propagation.REQUIRED, 
                       isolation = Isolation.DEFAULT, 
                       readOnly = false)
        public int saveAll(){
            //do stuff;
            if(oops == true) {
                 sessionContext.setRollbackOnly();
                 return;
            }
        }
    

    setRollbackOnly() is a member of EJBContext. SessionContext extends EJBContext: http://java.sun.com/j2ee/1.4/docs/api/javax/ejb/SessionContext.html Note it's only available in session EJBs.

    @Resource is a standard Java EE annotation, so you should probably check your setup in Eclipse. Here's an example of how to inject the SessionContext using @Resource.

    I suspect that this is probably not your solution, since it seems like you may not be working with EJBs -- explaining why Eclipse is not finding @Resource.

    If that's the case, then you will need to interact with the transaction directly -- see transaction template.

提交回复
热议问题