You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user-java@ibatis.apache.org by Rick <ri...@gmail.com> on 2009/08/23 00:54:15 UTC

Help creating a Guice TransactionInterceptor

Just wondering if anyone has worked on a Guice transaction interceptor
yet for i3 ? My progress so far...

I want to avoid:

public FooBar update(FooBar fooBar) {
    SqlSession session = sqlSessionFactory.openSession(ExecutorType.REUSE);
    try {
       FooBarMapper mapper = session.getMapper(FooBarMapper.class);
       mapper.update(fooBar);
       session.commit();
    } finally {
        session.close();
    }
}

So I started with an Interceptor like:

public class TransactionInterceptor implements MethodInterceptor {

    @Inject
    SqlSessionFactory sqlSessionFactory;

    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.REUSE);
        try {
           return methodInvocation.proceed();
        } finally {
            session.commit();
            session.close();
            System.out.println("session closed");
        }
    }
}

//the annotation
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
public @interface Transaction { }

//sample usage
@Transaction
    public Employee getEmployeeById(int id) {
       EmployeeMapper mapper = getSession().getMapper(EmployeeMapper.class);
       return mapper.getEmployeeById(id);
    }

Couple problems though:

1) How can I pass the interceptor the correct SqlSessionFactory since
you could have different ones for different DBs?
In my Module I have:

TransactionInterceptor transIntcp = new TransactionInterceptor();
requestInjection(transIntcp);
bindInterceptor(Matchers.any(),
Matchers.annotatedWith(Transaction.class),transIntcp);

somehow I need a way to annotate a method with:

@Transaction(@Named("MyDB"))
and then end up with the correct sqlSessionFactory injected?

I currently set up my different dbs with a different sqlSessionFactory
using a provider like:
SqlSessionFactoryProvider myDbProvider = new
SqlSessionFactoryProvider("mydb-ibatis-config.xml");
        bind(SqlSessionFactory.class).annotatedWith(Names.named("MyDB"))
                .toProvider(myDbProvider);



2) Look how I have to open the session twice.. once in the method call
of a dao to get the Mapper and then again in the Interceptor so that I
can close the session. This seems messed up for sure, although it's
not really breaking anything, but I'm sure doing something improper
behind the scenes.

Anyone more familiar with guice have ideas how to tackle this? I'm a
Guice newbie so I'm probably missing obvious things.

---------------------------------------------------------------------
To unsubscribe, e-mail: user-java-unsubscribe@ibatis.apache.org
For additional commands, e-mail: user-java-help@ibatis.apache.org