Skip to content

Instantly share code, notes, and snippets.

@MirkoRossini
Created September 29, 2016 13:29
Show Gist options
  • Save MirkoRossini/e6d5eb91f09d5989cb5a60c54998c272 to your computer and use it in GitHub Desktop.
Save MirkoRossini/e6d5eb91f09d5989cb5a60c54998c272 to your computer and use it in GitHub Desktop.
package com.mirkorossini.transactionaltest;
import com.google.inject.*;
import org.apache.ibatis.session.SqlSessionManager;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.guice.MyBatisModule;
import org.mybatis.guice.datasource.builtin.PooledDataSourceProvider;
import org.mybatis.guice.datasource.helper.JdbcHelper;
import org.mybatis.guice.transactional.Transactional;
import javax.inject.Inject;
public class MyBatisTransactionalTest {
private static final String ENV = "test";
private final static Module MY_BATIS_MODULE = new MyBatisModule() {
@Override
protected void initialize() {
environmentId(ENV);
install(JdbcHelper.H2_EMBEDDED);
bindDataSourceProviderType(PooledDataSourceProvider.class);
bindTransactionFactoryType(JdbcTransactionFactory.class);
}
};
public interface MyInterface {
boolean isTransactional();
}
public static class MyImplementation implements MyInterface {
private final SqlSessionManager sqlSessionManager;
@Inject
public MyImplementation(final SqlSessionManager sqlSessionManager
) {
this.sqlSessionManager = sqlSessionManager;
}
@Transactional
@Override
public boolean isTransactional() {
return sqlSessionManager.isManagedSessionStarted();
}
}
private static void testTransactional(final Module privateModule) {
final Injector injector = Guice.createInjector(
Stage.DEVELOPMENT, privateModule);
if (!injector.getInstance(MyImplementation.class).isTransactional()) {
throw new RuntimeException("Not transactional");
};
}
public static void main (String[] args) {
final Module privateModule = new PrivateModule() {
@Override
protected void configure() {
install(MY_BATIS_MODULE);
bind(MyImplementation.class);
expose(MyImplementation.class);
expose(SqlSessionManager.class);
}
};
testTransactional(privateModule);
final Module privateModuleBindingTheinterface = new PrivateModule() {
@Override
protected void configure() {
install(MY_BATIS_MODULE);
bind(MyInterface.class).to(MyImplementation.class);
expose(MyInterface.class);
expose(SqlSessionManager.class);
}
};
testTransactional(privateModuleBindingTheinterface);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment