"MyBatis 3.5.2 Reference Document" study notes

Build SqlSessionFactory

Each MyBatis-based application is based on an  instance of SqlSessionFactory  as the core. The instance of SqlSessionFactory can be obtained through SqlSessionFactoryBuilder . The SqlSessionFactoryBuilder can construct an instance of SqlSessionFactory from an XML configuration file or an instance of a pre-customized Configuration.

Build from XML file 

It  is very simple to construct an instance of SqlSessionFactory from an XML file. It   is recommended to use the resource file under the classpath for configuration.     But you can also use any InputStream instance, including a file path in the form of a string or a file path in the form of a URL of file:// to configure. MyBatis includes a tool class called Resources, which contains some practical methods to make it easier to load resource files from the classpath or other locations.

String	resource="org/mybatis/example/mybatis-config.xml"; 
InputStream	inputStream	=Resources.getResourceAsStream(resource); 
SqlSessionFactory	sqlSessionFactory=new	SqlSessionFactoryBuilder().build(inputStream);

The XML configuration file contains the core settings for the MyBatis system, including the data source (DataSource) for obtaining database connection instances and the transaction manager (TransactionManager) that determines the scope and control method of the transaction .

Build SqlSessionFactory without using XML

Java class-based configuration


If there is an XML configuration file with the same name, MyBatis will automatically find and load it (in this example, BlogMapper.xml will be loaded based on the class path and the class name of BlogMapper.class).

Obtain SqlSession from SqlSessionFactory

SqlSession completely contains all the methods needed to execute SQL commands for the database. You can directly execute the mapped SQL statement through the SqlSession instance.


Explore mapped SQL statements

A statement can be defined either through XML or through annotations.

XML mapping

method one: 

 

Method Two: 

 

 There are two functions of the namespace, one is to use a longer fully qualified name to isolate different statements , and also to achieve interface binding.

Namespaces must be used to solve similar problems in different packages.

Annotation method mapping

Using annotations to map simple statements will make the code more concise. However, for slightly more complex statements, Java annotations are not enough and will appear more confusing. Therefore, if you need to accomplish very complex things, it is best to use XML to map the statement

The dependency injection framework can create thread-safe, transaction-based SqlSessions and mappers and inject them directly into your beans, so you can ignore their life cycles.

SqlSessionFactoryBuilder:

This class can be instantiated, used and discarded. Once the SqlSessionFactory is created, it is no longer needed. Therefore, the best scope of the SqlSessionFactoryBuilder instance is the method scope (that is, the local method variable). You can reuse SqlSessionFactoryBuilder to create multiple instances of SqlSessionFactory, but it is better not to let it always exist to ensure that all XML parsing resources can be released for more important things

 

SqlSessionFactory

Once the SqlSessionFactory is created, it should always exist during the running of the application. There is no reason to discard it or re-create another instance.  The best practice for using   SqlSessionFactory is not to recreate it multiple times during the running of the application . Rebuilding the SqlSessionFactory multiple times is regarded as a code "bad smell". Therefore    , the best scope of SqlSessionFactory is the application scope . There are many ways to do it, the easiest is to use singleton mode or static singleton mode.
 

SqlSession

Each thread should have its own instance of SqlSession. The instance of SqlSession is not thread-safe, so it cannot be shared, so its best scope is the request or method scope.     You must not put the reference of the SqlSession instance in the static field of a class, even the instance variables of a class. Never place the reference of the SqlSession instance in any type of managed scope, such as the HttpSession in the Servlet framework. If you are currently using a web framework, consider placing SqlSession in a scope similar to the HTTP request object. In other words, every time you receive an HTTP request, you can open a SqlSession, return a response, and then close it. This close operation is very important, and you should put this close operation in a finally block to ensure that it can be closed every time. The following example is a standard mode to ensure that SqlSession is closed:

 Mapper instance

Mappers are interfaces created by you that bind the statements you map . The instance of the mapper interface is obtained from SqlSession . The maximum scope of any mapper instance is the same as the SqlSession that requested them. Nevertheless, the best scope of the mapper instance is the method scope.  

 Configuration:

Settings:

Cache

MyBatis has built-in a powerful transactional query cache mechanism, which can be easily configured and customized.
By default, only the local session cache is enabled, which only caches the data in one session.    

To enable the global second-level cache, just add a line to your SQL mapping file:
  

 <cache/>

That's basically it. The effect of this simple statement is as follows:

  • The results of all select statements in the mapping statement file will be cached.
  • All insert, update, and delete statements in the mapped statement file will refresh the cache.
  • The cache will use the least recently used algorithm (LRU, Least Recently Used) algorithm to clear unnecessary cache.
  • The cache is not refreshed regularly (that is, there is no refresh interval).
  • The cache will hold 1024 references to lists or objects (regardless of which query method returns).
  • The cache is considered a read/write cache, which means that the acquired object is not shared and can be safely modified by the caller without interfering with potential modifications made by other callers or threads.

This more advanced configuration creates a FIFO buffer, refreshed every 60 seconds, and can store up to 512 references to the result object or list , and the returned objects are considered read-only, so modifying them may occur in different threads. The caller in has a conflict.
 

Use custom cache
 

<cache    type="com.domain.something.MyCustomCache"/>
  • The class specified by the type attribute must implement the org.mybatis.cache.Cache interface,
  • And provide a constructor that accepts a String parameter as id.    
  • This interface is one of many complex interfaces in the MyBatis framework, but its behavior is very simple.

SqlSession

Execute statement method

In short, each mapper method signature should match the associated SqlSession method, and the string parameter ID does not need to match. Instead, the method name must match the ID of the mapping statement.

You can pass multiple parameters to a mapper method. If you do this, by default they will be named after the "param" string followed by their position in the parameter list.

For example: #{param1}, #{param2}, etc.

If you want to change the name of the parameter (only in the case of multiple parameters), then you can use the @Param("paramName") annotation on the parameter.

SQL class

Log configuration

Guess you like

Origin blog.csdn.net/sanhewuyang/article/details/104814661