Thursday, June 26, 2014

MyBatis & Managed Transaction

How to work with Managed transaction in MyBatis?

MyBatis+Managed Transaction

public class BizService {
private SqlSessionFactory sqlSessionFactory;
/**
* Initalize the
*
* @param config the config
*/
private void init(QueryEngineConfiguration config) {
InputStream inputStream;
Properties properties= new Properties();
properties.setProperty("driver", config.getDriverClassName());
properties.setProperty("url", config.getDbUrl());
properties.setProperty("username", config.getDbUsername());
properties.setProperty("password", config.getDbPassword());
try(
inputStream = Resources.getResourceAsStream(config.getSqlMapConfigPath());
) {
this.sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream, properties);
}
}
public void bizFunction(SomeValueObject valueObject){
try (
SqlSession session = factory.openSession(false);
){
Entity1 entity1 = valueObject.getEntity1();
sqlSession.insert("insertQueryName1", entity1);
Entity2 entity = valueObject.getEntity2();
sqlSession.insert("insertQueryName2", entity);
session.commit();
}
}
}
view raw BizService.java hosted with ❤ by GitHub
<environments default="development">
<environment id="development">
<transactionManager type="MANAGED" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
...
</dataSource>
</environment>
</environments>
view raw sqlconfig.xml hosted with ❤ by GitHub

No comments:

Post a Comment