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);
- Spring Boot – University Book Keeping App , Part – 2 - January 14, 2017
- Spring Boot – University Book Keeping App , Part – 1 - January 14, 2017
- Spring Boot – University Book Keeping App - January 14, 2017
- A Shoot at Permgen & Metaspace - January 14, 2017
- Spark – Shell - January 2, 2017
- Spark – Concepts - January 2, 2017
- Spark – Sample Application in Windows - December 31, 2016
- MyBatis – Components - June 17, 2016
- Castor – Default Mapping - June 17, 2016