0

I am sort of beginner in MyBatis, and I was going through below link of their documentation:
MyBatis Getting Started

What it suggest is:

Each thread should have its own instance of SqlSession. Instances of SqlSession are not to be shared and are not thread safe.

From above line what I understood is, we should use it in this way:

SqlSession session = // getting one instance of SqlSession as suggested in above link  
List<Integer> result = session.selectList("getUsersId");
session.close();  

So similarly where ever required, I need to create new SqlSession each time and close them. is there any better way to use it ? From better way I mean a better way to write code, pattern which should create SqlSession for me and close it automatically.
(I am using Vaadin and MyBatis.)

Aman Gupta
  • 5,548
  • 10
  • 52
  • 88

3 Answers3

0

SqlSession lifetime scope is method or Http request. So if method is return or request completed, it will be close auto.

君主不是你
  • 452
  • 4
  • 19
0

SqlSession is AutoCloseable

When you use it try-with-resource, Autocloseable class invoke default close method

The correct pattern would be

try (SqlSession session = // getting one instance of SqlSession as suggested in above link) {
    List<Integer> result = session.selectList("getUsersId");
}
Languoguang
  • 2,166
  • 2
  • 10
  • 15
-1

Use ThreadLocal. With such an approach each thread will have its own SqlSession. Note that thread should cleanup after itself so closing an opened sql session should be a part of it.

More on this:

Community
  • 1
  • 1
wypieprz
  • 7,981
  • 4
  • 43
  • 46