This is the 27th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Factory mode for Mybatis design Mode
Factory model concept
In Mybatis, for example SqlSessionFactory uses factory mode, which is a simple factory mode with less complicated logic.
Simple Factory Pattern: Also known as Static Factory Method Pattern, it belongs to the creation Pattern.
In the simple factory pattern, you can return instances of different classes depending on the parameters. The simple factory pattern specifically defines a class that is responsible for creating instances of other classes, which usually have a common parent class.
Example: Making computers
Let’s say we have a contract manufacturer of computers that can already produce Lenovo computers. As the business expands, this contract manufacturer will also produce HP computers. We need a separate class to produce computers, which uses the simple factory model. Let’s implement the simple factory pattern:
-
- Create an abstract product class
We create an abstract product class for a computer that has an abstract method to boot the computer:
- 2. Create a product class
We then create each brand of Computer that inherits from its parent class Computer and implements the start method:
-
- Creating a Factory Class
Next create a factory class that provides a static method, createComputer, to produce the computer. All you need to do is pass in the brand of the computer you want to build, and it will instantiate that brand of computer object
The client calls the factory class, passing in “HP” to produce an HP computer and calling the start method on the computer object:
Mybatis reflect
The factory pattern is used in the creation of Mybatis to execute Sql statements, get Mappers, and SqlSession, the core interface to manage transactions.
A SqlSessionFactory is responsible for creating sqlSessions
SqlSessionFactory as you can see, the Factory openSession () method is overloaded to support the input of parameters such as autoCommit, Executor, Transaction, etc., to build the core SqlSession object.
In the default factory implementation of DefaultSqlSessionFactory, there is a method to see how the factory produces a product:
This is a low-level method called by openSession that reads the corresponding environment configuration from Configuration and then initializes the TransactionFactory to get a Transaction object, Then Transaction is used to obtain an Executor object, and SqlSession is constructed using the configuration, Executor, and autoCommit parameters. So far, the method of using factory mode in Mybatis has been clarified, and there are many other places in Mybatis that also use M factory mode, so it will not be analyzed.