简体   繁体   中英

How to exclude a method to be @Transactional?

In service layer, we got

@Service
@Transactional(readOnly = false)
public abstract class GenericService

In repository layer, we got

public abstract class GenericRepository

In service we have a save method that calls the save method of repository, which is

@Override
   public void savePersist(T entity) {

      getSession().persist(entity);
   }

All I want to do is to save the object "entity" into hibernate session for further processing, without commit or any insert statement into database. but what actually happens is saving "entity" after running the savePersist(). I think this because of using @Transactional annotation on service class. But what should I do for save the entity in session?

When you just want Spring not commit the transaction, then you need to roleback the Transaction. There are several ways:

  • Throwing a Runtime Exception (within the Method that has the @Transactional annotation) - but this is a bit of abusing the roleback mechanism
  • an other way is to mark the Transaction as readOnly : @Transactional(readOnly = true)

But this both works only for the complete session!

The other way is to make the entity read only: https://docs.jboss.org/hibernate/orm/3.5/reference/de-DE/html/readonly.html#readonly-api

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