I am using Mybatis to make a CRUD application for a database and since all of my methods contain repetitive code when opening and closing an SQL session I would like to use an invocation handler to minimize the code repetition. Almost all of my methods look something like this:
public int deleteDefDialog(DefDialog defDialog) {
SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory()
.openSession();
try {
DialogMapper dialogMapper = sqlSession
.getMapper(DialogMapper.class);
int i = dialogMapper.deleteDefDialog(defDialog);
sqlSession.commit();
return i;
} finally {
sqlSession.close();
}
}
public DefDialog selectDefDialog(BigDecimal i) {
SqlSession sqlSession = ConnectionFactory.getSqlSessionFactory()
.openSession();
try {
DialogMapper dialogMapper = sqlSession
.getMapper(DialogMapper.class);
return dialogMapper.selectDefDialog(i);
} finally {
sqlSession.close();
}
}
My question is how do I properly write and call the invocation handler, keeping in mind that the application remains thread-safe?
I solved the problem so I will answer my own question, the proper way to open and close an sql session using an invocation handler was to store the sqlSession in ThreadLocal.
ConnectionHandler.java
and change the above class to
DialogServiceImpl.java
and call the function like this