Explanation of java mybatis Framework Configuration

  • 2021-08-12 02:41:00
  • OfStack

The use of a framework cannot be separated from the component support. After downloading the mybatis framework, we have to configure it manually because most of the internal structure has not yet started. As mentioned earlier, the role of mybatis framework has database, so this article brings the configuration method of database and sql. Let's take a look at the specific operation below.

1. Configure the database

Create the configuration file of mybatis and configure the information of database. We can configure multiple databases, but only one can be used by default.


<?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>
<!--  Load the properties file under the classpath  -->
<properties resource="db.properties"/>
<!--  Settings 1 Default connection environment information  -->
<environments default="mysql_developer">
<!--  Connect environment information, take 1 Arbitrary only 1 The name of  -->
<environment id="mysql_developer">
<!-- mybatis Use jdbc Transaction management mode  -->
<transactionManager type="jdbc"/>
<!-- mybatis Use connection pooling to get connections  -->
<dataSource type="pooled">
<!--  Object that interacts with the database 4 Required attributes  -->
<property name="driver" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.username}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
<!--  Connect environment information, take 1 Arbitrary only 1 The name of  -->
<environment id="oracle_developer">
<!-- mybatis Use jdbc Transaction management mode  -->
<transactionManager type="jdbc"/>
<!-- mybatis Use connection pooling to get connections  -->
<dataSource type="pooled">
<!--  Object that interacts with the database 4 Required attributes  -->
<property name="driver" value="${oracle.driver}"/>
<property name="url" value="${oracle.url}"/>
<property name="username" value="${oracle.username}"/>
<property name="password" value="${oracle.password}"/>
</dataSource>
</environment>
</environments>
</configuration>

2. Configure SqlSessionFactory

The SqlSessionFactory interface of the MyBatis can also be programmatically created via the Java API in addition to being created using the XML-based configuration. Every element configured in XML can be created programmatically.

Create an SqlSessionFactory using Java API with the following code:


public static SqlSessionFactory getSqlSessionFactoryUsingJavaAPI() {
  if (javaSqlSessionFactory == null) {
    try {
      DataSource dataSource = DataSourceFactory.getDataSource();
      TransactionFactory transactionFactory = new JdbcTransactionFactory();
      Environment environment = new Environment("development", transactionFactory, dataSource);
      Configuration configuration = new Configuration(environment);
      configuration.getTypeAliasRegistry().registerAlias("student", Student.class);
      configuration.getTypeHandlerRegistry().register(PhoneTypeHandler.class);
      configuration.addMapper(StudentMapper.class);
      javaSqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  return javaSqlSessionFactory;
}

In this configuration, 1 mapping class is loaded. The mapping class is an Java class that contains SQL mapping annotations and can be used to replace XML. However, due to the limitations of Java annotations and the complexity of MyBatis mappings, some advanced mappings, such as nested mappings, are still configured with XML. For this reason, MyBatis automatically finds and loads an existing XML.

Content extension:

Mybatis Parameter Setting

Problems needing attention in adding database
① Primary key self-increment: You can set primary key self-increment when creating database tables

② Primary key is not self-added: you can set it manually


<insert id="save" parameterType="Book" keyColumn="id" keyProperty="id" useGeneratedKeys="true">
    insert into jpa_book (author,createTime,name,price,sales,stock) values (#{author},#{createTime},#{name},#{price},#{sales},#{stock});
  </insert>

keyColumn= "id" Specifies the database table primary key field

keyProperty= "id" sets the attribute name of the entity class corresponding to the database table

useGeneratedKeys= "true" turn on primary key self-increment

③ Primary key does not support self-increment: For example, Oracle database does not support self-increment


<selectKey keyProperty="id" resultType="int" keyColumn="id"  order="BEFORE"> 
        select LAST_INSERT_ID <!-- Or use  select UUID() Generate -->
      </selectKey>

order= "BEFORE" indicates that the primary key is formed by the primary key and then self-increment is performed

select LAST_INSERT_ID or use select UUID () to generate a primary key value through a function


Related articles: