0

There is an existing code in my project it calls the mysql function. mysql function updates the value in a table.

function next_val (input varchar(10))
returns decimal(5,0)
begin
     update table set val = (@next_val := next_val) + inc where name = input;
     return @next_val;
end

In Spring code, I call the function using javax.entitymanager

em.createNativeQuery("select next_val('DB') from dual");

I am invoking the above method using @transactional annotation but this call auto commits the function result.

I couldn't revoke on any error

  • Do you have a JPA transaction manager configured for your Spring context? Where do you call the transactional method from (from some other method of the same bean)? – Ján Halaša Mar 02 '18 at 07:26
  • @Ján Halaša Yes. JPA transaction manager is configured. This is called from some other method of the same bean – newstackoverflowuser5555 Mar 02 '18 at 07:40
  • can you share with us snippet from you method make the call, is transactional behaviour work for others method ? – elmehdi Mar 02 '18 at 09:53

1 Answers1

1

You must call the @Transactional method from another bean and the method must be public. See the Spring docs:

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional. Also, the proxy must be fully initialized to provide the expected behaviour so you should not rely on this feature in your initialization code, i.e. @PostConstruct.

You can get around it by using AspectJ instead of the default proxy mode.

Ján Halaša
  • 8,167
  • 1
  • 36
  • 36
  • I am calling from different bean now and Having public method. Still transaction commit automatically. Is there something to do with Function ? – newstackoverflowuser5555 Mar 02 '18 at 08:58
  • Then you can try to debug the transactional method and set a breakpoint there. You should see `TransactionAspectSupport.invokeWithinTransaction()` somewhere higher in the call stack. If the method is not there, or it's `transactionManagerBeanName` property is not correct, your Spring context is not correctly configured. You can also check that you have just one TransactionManager configured for the context. – Ján Halaša Mar 02 '18 at 09:52