Skip to content
Advertisement

How to not persist sqlSession.selectOne returned value?

My goal is to not persist the SqlSession.selectOne returned value. The problem is, if you do a sqlSession.selectOne (using an API endpoint) and then you edit the database directly for example using the MySQL workbench. After you edit the database and do another API endpoint request, the returned value will not change.

This is how you recreate the problem:

  1. Do get request to the endpoint. The returned value is false.
  2. Update the database so if you do a get request again, the returned value should be true. Instead it returned false.

The only way to fix this is to restart the server, which is not feasible.

This is how I do a sqlSession.selectOne:

  1. boolean value = sqlSession.selectOne(params);
  2. sqlSession.commit();
  3. return value;
JavaScript

mybatis-config.xml

JavaScript

build/admin/Admin_LogginMapper.xml

JavaScript

What I’ve did:

  1. tried to do sqlSession.close(); // this will lead to error.
  2. tried to do sqlSession.clearCache(); // does not help.

I can’t afford to:

  1. Remove the @Repository and manually create new object Admin_LoginImpl for every rest endpoint request. This will significantly increase the response time.

Advertisement

Answer

This problem happens because you create one SqlSession in Admin_LoginImpl and reuse it. This is not the recommended way to use mybatis. By default mybatis uses cache that is bound to session so if you repeat the same query it will return cached result.

Session creation is not a heavy weight operation and should be done once per request. The problem with performance that you faced is caused not by session creation by because SqlSessionFactory creation takes time.

To solve the problem you can keep SqlSessionFactory creation in the constructor of you repository but create SqlSession for every transaction.

Yet a better solution is to use MyBatis-Spring integration which will give you proper integration with spring and session management for free.

Advertisement