MyBatis – Components


Before writing any MyBatis application you need to understand the components which build the application. Once you understand the components you are good to go. So lets discuss each component one by one.

In MyBatis the SqlSession is equivalent to a JDBC connection, or Hibernate Session.Basically the entry point of any MyBatis application. Responsible for executing the commands, managing transactions etc.
They are not thread safe.So, shouldnot be shared among multiple threads. Ideally each thread should have their own SqlSession.
When you work with a SqlSession make sure you follow some rules such as- always close the SqlSession from within a finally block. Don’t keep any reference to a SqlSession instance from a static field or instance field.
If you have a web application then its a best practice to have the SqlSession scope similar to request scope i.e for each Http request create a session and close it.

The factory class for building a SqlSession. Again equivalent to SessionFactory in Hibernate, DataSource in JDBC .Ideally each database configuration has a single SqlSessionFactory.It returns an instance of SqlSession when you call the openSession() method.

A builder class which is used for building instance of SqlSessionFactory. The SqlSessionFactory can be created in 2 ways:-

  • using the xml approach:-in this case put all the configuration in the xml file and pass the xml file as inputstream to the builder instance.
    ¬†InputStream inputStream = Resources.getResourceAsStream(“org/technovillage/example/mybatis-config.xml” );
     SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
  • using the configuration class approach:-
    Configuration configuration = new Configuration(environment);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);


Related Post

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu Title