1

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?

Khoda
  • 955
  • 2
  • 14
  • 42
  • Is this desired behavior for all situations or just for specific case? In any case ```savePersist(T entity)``` method is designated to save and commit the changes, so if you want behavior other than this for specific situation, it's better to look for other solutions. For example you can have some proxy service with ```readOnly=true``` , which will call ```GenericRepository.savePersist(T entity)``` as a result spring will carry the proxy and will not create a new transaction, so the entity will not be committed. – vtor Feb 01 '15 at 12:54

1 Answers1

2

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

Ralph
  • 118,862
  • 56
  • 287
  • 383