views:

80

answers:

2

Hello experts!

My class is annotated with org.springframework.transaction.annotation.Transactional like this:

@Transactional(readOnly = true)
public class MyClass {

I then have a dao class:

@Override
public void delete(final E entity) {
    getSession().delete(entity);
}

@Override
public void save(final E entity) {
    getSession().saveOrUpdate(entity);
}

Then I have two methods in MyClass

@Transactional(readOnly = false)
public void doDelete(Entity entity){
    daoImpl.delete(entity)
}

//@Transactional(readOnly = false)
public void doSave(){
    daoImpl.save(entity)
}

Saving and deleting works like a charm. But if I remove the @Transactional(readOnly = false) on doDelete method deletion stops working, Saving works with and without the method annotation. So my question is: WHY?

A: 

The question is why save still works without method annotation as your whole class is set to readOnly=true. Maybe you have some default transactional setting in your xml config saying that all methods that start with "save" are not read only? Like this:

<tx:advice id="txAdvice" transaction-manager="txManager">
  <tx:attributes>
     <tx:method name="save*" read-only="false" />
     ...
  </tx:attributes>
</tx:advice>
serg
Hi! I don't have any xml config, except from my applicationContext.xml since I use annotations. Could it be a bug in Hibernate?
jakob
A: 

You have defined annotations as follows;

@Transactional(readOnly = true)
public class MyClass {

    @Transactional(readOnly = false)
    public void doDelete(Entity entity){
        daoImpl.delete(entity)
    }

    //@Transactional(readOnly = false)
    public void doSave(){
        daoImpl.save(entity)
    }
}

If an @Transactional is defined at a class level, then all the methods in the class inherit the same transaction property. Explicitly defining @Transaction(readOnly = false) overrides this default property, giving the method edit rights.

You should be careful when defining @Transactional at a class level, can cause some debugging woes if not handled carefully.

Varun Mehta