Collate some important features and basic usage examples from Java's MyBatis framework

  • 2020-05-07 19:49:39
  • OfStack

Review of basic usage of :
The
SQL statement is stored in an XML file or in an Java annotation. 1 example of MaBatis mapping (where Java interface and MyBatis annotations are used) :


package org.mybatis.example;

public interface BlogMapper {
  @Select("select * from Blog where id = #{id}")
  Blog selectBlog(int id);
}

Example of execution:


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);

SQL statements and maps can also be externalized to 1 XML file:


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" parameterType="int" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

You can also use MyBatis API to execute statements:


Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);

Details can be found in the user manual provided on the MyBatis website.


integrates with Spring
MyBatis integrates with Spring Framework. Spring Framework allows MyBatis to participate in Spring transactions, creates MyBatis mapper and session, and injects them into other bean.

Here is an example of a basic XML configuration: a mapper is created and injected into "BlogService" bean.


<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

<bean id="blogMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="mapperInterface" value="org.mybatis.example.BlogMapper" />
</bean>

<bean id="blogService" class="org.mybatis.example.BlogServiceImpl">
  <property name="blogMapper" ref="blogMapper" />
</bean>

Now you only need to call 1 bean to call MyBatis:


public class BlogServiceImpl implements BlogService {

  private BlogMapper blogMapper;

  public void setBlogMapper(BlogMapper blogMapper) {
    this.blogMapper = blogMapper;
  }

  public void doSomethingWithABlog(int blogId) {
    Blog blog = blogMapper.selectBlog(blogId);
    ...
  }
}

SqlSessionFactory
each MyBatis program takes an example of an SqlSessionFactory pair of images as the core. SqlSessionFactory itself is created by SqlSessionFactoryBuilder. Generally speaking, in one application, one database will only correspond to one SqlSessionFactory, so we define SqlSessionFactory as a singleton mode or inject it through Spring.
SqlSessionFactoryBuilder creates SqlSessionFactory by:

SqlSessionFactory build(InputStream inputStream)   SqlSessionFactory build(InputStream inputStream, String environment)   SqlSessionFactory build(InputStream inputStream, Properties properties)   SqlSessionFactory build(InputStream inputStream, String env, Properties props)   SqlSessionFactory build(Configuration config)    

The main parameters to be designed for these methods are InputStream, environment and properties. InputStream is an input stream obtained from the configuration file. environment indicates which environment, including data sources and transactions, is currently used among the many environment configured in the configuration file. By default, environment is used. With properties, MyBatis loads corresponding properties or files that can be used in configuration files.  
 
 
builds SqlSessionFactory from XML


private static SqlSessionFactory sqlSessionFactory = null; 
   
  static { 
    try { 
      InputStream is = Resources.getResourceAsStream("config/mybatis_config.xml"); 
      sqlSessionFactory = new SqlSessionFactoryBuilder().build(is); 
    } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
     
  } 
   
  public static SqlSessionFactory getSqlSessionFactory() { 
    return sqlSessionFactory; 
  } 

 
Here's the basic structure of a configuration file:
Configuration file 1 of mybatis includes the following sections:

properties: properties is used to define or import properties and then use them in later environments settings:settings is used to set the behavior of some mybatis at runtime. You can see the documentation of mybatis for the specific setting information typeAliases:typeAliases specifies a short alias for the Java type in the system environments:MyBatis can be configured in a variety of environments. This will help you apply the SQL map to a variety of databases.

<environments default="development"> 
    <environment id="development"> 
      <transactionManager type="JDBC" /> 
      <dataSource type="POOLED"> 
        <property name="driver" value="${jdbc.driver}" /> 
        <property name="url" value="${jdbc.url}" /> 
        <property name="username" value="${jdbc.username}" /> 
        <property name="password" value="${jdbc.password}" /> 
      </dataSource> 
    </environment> 
  </environments> 

Since MyBatis can be configured with more than one environment, you can specify a specific environment to create SqlSessionFactory in a specific environment when SqlSessionFactory is created, and   USES the default environment if   is not specified.
transactionManager

There are two transaction manager types in MyBatis (i.e. type= "[JDBC|MANAGED]"):

The JDBC wok configuration simply USES JDBC's commit and rollback Settings. It relies on connections from the data source to manage the transaction scope.
The MANAGED wok configuration does very little. It never commits or rolls back 1 connection. Instead, it lets the container manage the transaction's entire life cycle (such as the context of an Spring or JEE application server), and by default it closes the connection. However, some containers do not want this, so if you need to stop it from the connection, set the closeConnection property to false.
dataSource

The dataSource element USES the basic JDBC data source interface to configure the resources of the JDBC connection object.

Many MyBatis applications will configure the data source according to the example in the example. However, it is not necessary. Be aware that the data source is required to facilitate lazy loading.
There are three built-in data source types (i.e. type= "? The & # 63; The & # 63;" ) :

The implementation of the UNPOOLED wok data source is to simply open and close the connection each time it is requested. It's 1 point slow, which is a good choice for simple applications because it doesn't require a timely available connection. Different databases also behave differently to this one, so for some databases it is not important to configure the data source, and the configuration is idle. The UNPOOLED type data source is only used to configure the following five properties:

This is the fully qualified name of the JDBC driver's Java class (if your driver contains it, it is not a data source class either). This is the JDBC URL address of the database. username the user name of the logged-in database. password the password to the database. The default connection transaction isolation level for defaultTransactionIsolationLevel wok.

Optionally, you can pass database-driven properties. To do this, properties are prefixed with "driver." for example:


driver.encoding=UTF8

This is passed to the database driver via the DriverManager.getConnection (url,driverProperties) method.

This is an implementation of the data source connection pool for the JDBC connection object to avoid the initial connection and authentication time necessary to create a new connection instance. This is a popular way for Web applications to quickly respond to requests.

In addition to the above (UNPOOLED) properties, there are many other properties that can be used to configure the POOLED data source:

The number of active (that is, in use) connections that exist at any time from the poolMaximumActiveConnections wok. Default value: 10 Number of free connections at any time. The time at which connections in the pool are checked before the poolMaximumCheckoutTime wok is forced to return. Default value :20000 milliseconds (i.e. 20 seconds) This is a low-level setting to give the connection pool a chance to print log status, and to retry to get the connection, which often takes a long time to avoid a silent failure if the connection pool is not configured. Default value :20000 milliseconds (i.e. 20 seconds) The poolPingQuery message sends a probe query to the data to verify that the connection is working and ready to accept the request. The default is "NO PING QUERY SET", which causes many database-driven connections to fail due to an error message. This is to enable or disable the detection of queries. If enabled, you must set the poolPingQuery property with 1 valid SQL statement (preferably fast). Default :false. This is used to configure poolPingQuery multiple times to be used once. This can be set to match the standard database connection timeout to avoid unnecessary detection. Default: 0(that is, all connections are detected every 1 - but only if poolPingEnabled is true). This data source, JNDI, is implemented to use containers such as Spring or application servers, which can set or configure the data source externally, and then place a reference to the JNDI context.

The JNDI data source configuration requires only two generalities:

(1) initial_context this genus is used to find the environment from the beginning (initialContext.lookup (initial -- context). This is an optional property, and if it is ignored, the data_source property will be looked for again directly in the context of initialContext.
(2) data_source this is the path to the context that references the location of the data source instance. It looks in the context of the environment returned by the initial_context query, and if initial_context does not return a result, it looks directly in the original context.
Then there's Mapper, Mapper, which maps to SQL statements, and the first thing to do is to tell mybatis where to find these SQL statements, which specifies the resource location.


<mappers> 
    <mapper resource="com/tiantian/mybatis/model/BlogMapper.xml"/> 
  </mappers>  

Here is a simple configuration file I used during the test:


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
0

 
In the above configuration file, an external properties file is imported. The introduction of attributes in MyBatis configuration file can be directly included in the properties element, or it can be imported from the outside with the properties element, or it can be passed in as a parameter properties when SqlSessionFactory is created. Since the attributes in the MyBatis profile can be imported from so many places, there is a priority involved, and MyBatis will look for them in the following order:
First, in the configuration file, the properties in the properties element body are read
Then the attributes in the properties file are read using the properties element, imported from the outside, overwriting the same attributes that were read earlier
Finally, when SqlSessionFactory is created, the attributes passed in properties are read, again overwriting the same attributes

After having SqlSessionFactory, it is necessary to obtain SqlSession. In the process of using mybatis, every operation is inseparable from SqlSession, so it is quite important to obtain SqlSession. In addition, SqlSession cannot be Shared and threads are not safe, so you should open one every time you need SqlSession and close it when you are done.


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
1

 
SqlSessionFactory middle lake SqlSession methods are:

SqlSession openSession()   SqlSession openSession(boolean autoCommit)   SqlSession openSession(Connection connection)   SqlSession openSession(TransactionIsolationLevel level)   SqlSession openSession(ExecutorType execType,TransactionIsolationLevel level)   SqlSession openSession(ExecutorType execType)   SqlSession openSession(ExecutorType execType, boolean autoCommit)   SqlSession openSession(ExecutorType execType, Connection connection)   Configuration getConfiguration();  

The main differences are:

Transaction (transactions): you want to use transactions or use auto-commit for session Connection (connection): do you want MyBatis to get a connection from the configured data source or provide it yourself Execution (execution): you want MyBatis to reuse preprocessing statements and/or batch update statements (including insert and delete)

The   default opensession method has no arguments, and it creates SqlSession with the following characteristics:

Will open 1 transaction, that is, will not commit automatically The connection object is obtained from the data source currently in use in environment The transaction isolation level will use the default values for the driver or data source Preprocessed statements are not reused, nor are batch update statements

ExecutorType has three values:

ExecutorType.SIMPLE creates a new preprocessing statement for each statement execution ExecutorType.REUSE multiplexes preprocessing statements ExecutorType.BATCH this actuator executes the update statement in batches

The basic operation of mybatis is to add, delete, change and check insert, delete, update and select. These basic operations can be performed by directly accessing the map in the Mapper configuration file using SqlSession, or by using the Mapper interface corresponding to the Mapper configuration file, provided that the parameters and return values of the methods defined in the Mapper interface are the same as those defined in the Mapper configuration file. In addition, when using the Mapper interface, the corresponding SQL statement can be written in the Mapper configuration file or marked directly on the corresponding method in the Mapper interface using the corresponding annotation, as you will see in the following sample code.

here is the sample code for the 1 series:
first paste 1 tool class to get SqlSessionFactory:


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
2

 
Configuration file for mybatis:


<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration 
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 
<configuration> 
  <properties resource="config/jdbc.properties"></properties> 
  <typeAliases> 
    <typeAlias alias="Blog" type="com.tiantian.mybatis.model.Blog"/> 
  </typeAliases> 
  <environments default="development"> 
    <environment id="development"> 
      <transactionManager type="JDBC" /> 
      <dataSource type="POOLED"> 
        <property name="driver" value="${jdbc.driver}" /> 
        <property name="url" value="${jdbc.url}" /> 
        <property name="username" value="${jdbc.username}" /> 
        <property name="password" value="${jdbc.password}" /> 
      </dataSource> 
    </environment> 
  </environments> 
  <mappers> 
    <mapper resource="com/tiantian/mybatis/model/BlogMapper.xml"/> 
  </mappers> 
</configuration> 

 
BlogMapper.xml


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
4

Some things to watch out for in SQL mapping statements:

The value of   resultType should be the full name or alias of the return type, and when the result returned is a collection, resultType should be the type contained in the collection, not the collection type, as Blog above Both resultType and resultMap represent the specified return result, but both cannot be used at the same time Have a useGeneratedKeys properties for Insert mapping statement, the default value of this attribute is false, when the value of the attribute for true, when making the insert, mybatis will take to the current is inserted into the records in the database automatically incrementing the primary key, and set it to specify the properties of the entity, it is need to set up a keyProperty properties, said primary key attribute is used to specify the entity

Blog.java


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
5

 
BlogMapper.java


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
6

 
Test1.java


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
7

 
Test2.java


package com.tiantian.mybatis.test; 
 
import java.util.List; 
 
import org.apache.ibatis.session.SqlSession; 
import org.junit.Test; 
 
import com.tiantian.mybatis.model.Blog; 
import com.tiantian.mybatis.model.BlogMapper; 
import com.tiantian.mybatis.util.Util; 
 
/** 
 *  The series of operations is to SQL The statement is written in the configuration file,  
 *  And then through correspondence Mapper Interface to operate on  
 * @author andy 
 * 
 */ 
public class Test2 { 
 
  /** 
   *  The new record  
   */ 
  @Test 
  public void testInsertBlog() { 
    SqlSession session = Util.getSqlSessionFactory().openSession(); 
    Blog blog = new Blog(); 
    blog.setTitle(" The Chinese "); 
    blog.setContent("5 Thousand years of wind and rain ah hide many dreams "); 
    blog.setOwner(" Day after day "); 
    BlogMapper blogMapper = session.getMapper(BlogMapper.class); 
    blogMapper.insertBlog(blog); 
    session.commit(); 
    session.close(); 
  } 
 
  /** 
   *  Query a single record  
   */ 
  @Test 
  public void testSelectOne() { 
    SqlSession session = Util.getSqlSessionFactory().openSession(); 
    BlogMapper blogMapper = session.getMapper(BlogMapper.class); 
    Blog blog = blogMapper.selectBlog(7); 
    System.out.println(blog); 
    session.close(); 
  } 
 
  /** 
   *  Modify the record  
   */ 
  @Test 
  public void testUpdateBlog() { 
    SqlSession session = Util.getSqlSessionFactory().openSession(); 
    Blog blog = new Blog(); 
    blog.setId(9);//  In need of modification Blog the id 
    blog.setTitle(" The Chinese 2");//  Modify the Title 
    blog.setContent(" Yellow face, black eyes, the same is a smile ");//  Modify the Content 
    blog.setOwner(" Day after day 2");//  Modify the Owner 
    BlogMapper blogMapper = session.getMapper(BlogMapper.class); 
    blogMapper.updateBlog(blog); 
    session.commit(); 
    session.close(); 
  } 
 
  /** 
   *  Query all records  
   */ 
  @Test 
  public void testSelectAll() { 
    SqlSession session = Util.getSqlSessionFactory().openSession(); 
    BlogMapper blogMapper = session.getMapper(BlogMapper.class); 
    List<Blog> blogs = blogMapper.selectAll(); 
    for (Blog blog : blogs) 
      System.out.println(blog); 
    session.close(); 
  } 
 
  /** 
   *  Fuzzy query  
   */ 
  @Test 
  public void testFuzzyQuery() { 
    SqlSession session = Util.getSqlSessionFactory().openSession(); 
    BlogMapper blogMapper = session.getMapper(BlogMapper.class); 
    String title = " China "; 
    List<Blog> blogs = blogMapper.fuzzyQuery(title); 
    for (Blog blog : blogs) 
      System.out.println(blog); 
    session.close(); 
  } 
 
  /** 
   *  Delete records  
   */ 
  @Test 
  public void testDeleteBlog() { 
    SqlSession session = Util.getSqlSessionFactory().openSession(); 
    BlogMapper blogMapper = session.getMapper(BlogMapper.class); 
    blogMapper.deleteBlog(10); 
    session.commit(); 
    session.close(); 
  } 
 
} 

 
Test3.java


BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
9

Corresponding predicative sentences:


CREATE TABLE `t_blog` ( 
 `id` int(11) NOT NULL AUTO_INCREMENT, 
 `title` varchar(255) DEFAULT NULL, 
 `content` varchar(255) DEFAULT NULL, 
 `owner` varchar(50) DEFAULT NULL, 
 PRIMARY KEY (`id`) 
) 


Related articles: