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

Mybatis & returning auto-generated IDs with inserts

How do I return auto-generated IDs inserted in table within the same insert API?

PostgreSQL+MyBatis+Insert+Autogenerated ID

CREATE TABLE BOOK (
ID SERIAL PRIMARY KEY,
NAME VARCHAR (50) UNIQUE NOT NULL,
TITLE VARCHAR (100),
DESCRIPTION VARCHAR (200)
);
view raw book.sql hosted with ❤ by GitHub
<mapper>
<select id="add_book" parameterType="map" resultType="map">
INSERT
INTO BOOK(NAME,TITLE,DESCRIPTION)
VALUES
(#{name},#{title},#{description})
RETURNING *;
</select>
<select id="add_book" parameterType="list" resultType="map">
INSERT
INTO BOOK(NAME,TITLE,DESCRIPTION)
VALUES
<foreach collection="list" item="item" index="index" open="" separator="," close="">
(#{item.name},#{item.title},#{item.description})
</foreach>
RETURNING *;
</select>
</mapper>
view raw sqlmap.xml hosted with ❤ by GitHub