James
James

Reputation: 12806

Spring programmatic transaction with parameter

I'm working on some data access logic with Spring, my question has to do with transactions. The transaction documentation http://static.springsource.org/spring/docs/2.5.x/reference/transaction.html shows that you can implement declarative or programmatic transactions. I've chosen to use the programmatic approach so that I have finer control over what is transacted.

The basic pattern looks like this:

Product product = new Product();
// load properties 

// how do I pass my product object instance to my anonymous method?   
transactionTemplate.execute(
      new TransactionCallbackWithoutResult() 
      {
       protected void doInTransactionWithoutResult (TransactionStatus status)
       {
        // transaction update logic here
        return;
       }}); 

Perhaps i'm going about this the wrong way but, my question is how can I pass arguments into the inner anonymous method? The reason I want to do this is so I can build up my object graph before starting the transaction (because transactions should be as short time wise as possible right? ) I only want a fraction of the logic to run in the transaction (the update logic).

[edit]

So far it seems my only choice is to use a constant variable, or just put all logic inside the anonymous delegate. This seems like a very common problem...how have you handled situations like this in your own code?

Upvotes: 4

Views: 2590

Answers (2)

tangens
tangens

Reputation: 39733

For things like this I use the following ObjectHolder:

public class ObjectHolder<T> {
    private T m_object;

    public ObjectHolder( T object ) {
        m_object = object;
    }

    public T getValue() {
        return m_object;
    }

    public void setValue( T object ) {
        m_object = object;
    }
}

Then you can use

final ObjectHolder<Product> productHolder = 
    new ObjectHolder<Product>( new Product() );

...and inside your anonymous class you can access your Product with

productHolder.getValue();

...or change it's instance with

productHolder.setValue( new Product() );

Upvotes: 3

axtavt
axtavt

Reputation: 242716

Declare it final. Anonymous inner classes have access to final local variables:

public void someMethod() {
    ...
    final Product product = new Product();
    ...
    transactionTemplate.execute( 
        new TransactionCallbackWithoutResult()  
        { 
            protected void doInTransactionWithoutResult (TransactionStatus status) 
            { 
                doSomething(product);
                return; 
            }}); 
    ...
}

Upvotes: 5

Related Questions