Introduction to mybatis

1, Environment construction

  create maven web project mybatis01 and add maven dependencies as follows.

<dependency>
    <groupid>org.mybatis</groupid>
    <artifactid>mybatis</artifactid>
    <version>3.4.6</version>
</dependency>
<dependency>
    <groupid>mysql</groupid>
    <artifactid>mysql-connector-java</artifactid>
    <version>5.1.38</version>
</dependency>
<dependency>
    <groupid>ch.qos.logback</groupid>
    <artifactid>logback-classic</artifactid>
    <version>1.2.3</version>
</dependency>

2, Data preparation

CREATE TABLE `pet` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `weight` double NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;
insert  into `pet`(`id`,`name`,`weight`) values (1,'tearful',4.5);
insert  into `pet`(`id`,`name`,`weight`) values (2,'In vain',5.6);
insert  into `pet`(`id`,`name`,`weight`) values (3,'black',7.8);
insert  into `pet`(`id`,`name`,`weight`) values (4,'Honghong',9);

3, Configure core profile

   configure the mybatis core configuration file: mybatis-conf.xml. Create this file in the resource directory. The contents are as follows:

<!--?xml version="1.0" encoding="UTF-8"?-->

<configuration>
    <environments default="development">
        <environment id="development">
        <transactionmanager type="JDBC">
            <datasource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver">
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis">
                <property name="username" value="root">
                <property name="password" value="123456">
            </property></property></property></property></datasource>
        </transactionmanager></environment>
    </environments>
</configuration>

be careful:

  the type of dataSource can be configured as one of its built-in types, UNPOOLED, POOLED and JNDI.

  UNPOOLED, MyBatis will create a new connection for each database operation and close it. This method is suitable for simple applications with only a small number of concurrent users.
  POOLED, MyBatis will create a database connection pool, and a connection in the connection pool will be used as a database operation. Once the database operation is completed, MyBatis will return this connection to the connection pool. This approach is often used in development or test environments.
  JNDI, MyBatis obtains the database connection from the application server to the configured JNDI data source dataSource. In a production environment, this approach is preferred.

4, Log configuration (optional)

  in order to monitor the execution of mybatis, we print the operation of relevant programs through logback. Add the log configuration file logback. Under resource xml

<!--?xml version="1.0" encoding="UTF-8"?-->
<configuration>
    <!--Console-->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5p --- [%t] %-40.40logger{39} : %m%n</pattern>
        </encoder>
    </appender>
    <!--root logger-->
    <root level="DEBUG" additivity="false">
        <appender-ref ref="console">
    </appender-ref></root>
</configuration>

  after adding the file, the operation status of mybatis, the SQL sent, the data filled in by SQL and the number of returned data are printed and displayed on the console.

5, Create entity

  create corresponding entities and add corresponding getter and setter methods. Because mybatis uses reflection to complete the encapsulation of objects, entities must need a parameterless construction method. If you need to output an object, you also need to override its toString method.

public class Pet{
    private Integer id;
    private String name;
    private Double weight 
}

6, Create Mapper file

  all database operations of mybatis are completed through mapper files. Mapper files are generally stored in the resource/mapper / directory.

  create the mapping file corresponding to the entity class * mapper XML, as shown in the following code:

<code><xmp><!--?xml version="1.0" encoding="UTF-8" ?-->
 
<mapper namespace="cn.hxzy.mapper.petMapper"> 
    <select id="getById" parametertype="int" resulttype="cn.hxzy.entity.Pet">
        select * from pet where id=#{id}
    </select>
</mapper>

  note:

  parameterType: parameter type

   resultType: method return type (if the return is a collection, the return type adds the full path of the type of the collection to store the object)

  whether it is a parameter type or a return type, the user-defined class needs to write the full pathname of the class.

7, Register mapper file

  register the above * mapper. In the mybatis core configuration file mybatis-conf.xml xml.

<mappers>
    <mapper resource="mapper/PetMapper.xml">
</mapper></mappers>

The following is an explanation of these configuration files:
1. The configuration file mybatis-conf.xml is used by mybatis to establish sessionFactory, which mainly contains contents related to database connection.
2. mybatis-conf.xml contains the XML configuration file containing the classes to be mapped.
3. In * mapper The XML file mainly defines various SQL statements, parameters of these statements, types to be returned, etc.

8, Run test

  create the main method and complete the relevant tests.

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MainTest {
    public static void main(String[] args) throws IOException {
        //Load the core configuration file of mybatis (it also loads the associated mapping file)
        Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
        //Build a factory for sqlSession
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //Create an sqlSession that can execute sql in the mapping file
        SqlSession session = sessionFactory.openSession();
        Object o = session.selectOne("cn.hxzy.mapper.petMapper.getById",3);
        System.out.println(o);
    }
}

be careful:

1. The original intention of selectone is to query a single. When multiple results appear during query, the following error will be reported: if the query is a collection, use the selectList method.

org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3

2.SqlSessionFactory thread safety can be designed as a singleton

3.SqlSession thread is unsafe and cannot be a public variable of a class
practice:

1. Create the project fruit01, create the fruit (id, name, color) entity and the corresponding database table in the project, and complete the functions of querying fruits and all fruits according to id.


Reference code:

pom. The XML code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>fruit01</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>8.5.59</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

</project>

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>mybatis</artifactId>
    <groupId>org.example</groupId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>

  <artifactId>fruit01</artifactId>

  <name>fruit01</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.48</version>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.2.6</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>3.0.0</version>
          <executions>
            <execution>
              <goals>
                <goal>java</goal>
              </goals>
            </execution>
          </executions>
          <configuration>
            <classpathScope>test</classpathScope>
          </configuration>
        </plugin>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>


App. The Java code is as follows:

package org.example;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) throws IOException {
        //Load the core configuration file of mybatis (it also loads the associated mapping file)
        Reader reader = Resources.getResourceAsReader("mybatis-conf.xml");
        //Build a factory for sqlSession
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //Create an sqlSession that can execute sql in the mapping file
        SqlSession session = sessionFactory.openSession();
        Fruit o = session.selectOne("com.allen.mapper.getById", 1);
        System.out.println(o.toString());
        List<Fruit> list = session.selectList("com.allen.mapper.findAll");
        System.out.println(list);
        session.close();
    }
}


The Fruit code is as follows:

package org.example;


public class Fruit {

  private Integer id;
  private String name;
  private String color;

  @Override
  public String toString() {
    return "Fruit{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", color='" + color + '\'' +
            '}';
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }


  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }

}


The fruitMapper code is as follows:

<?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="com.allen.mapper">
    <select id="getById" parameterType="int" resultType="org.example.Fruit">
        select * from fruit where id=#{id}
    </select>
    <select id="findAll" resultType="org.example.Fruit">
        select * from fruit
    </select>
</mapper>


The code of mybatis-conf.xml is as follows:

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/fruitMapper.xml"></mapper>
    </mappers>
</configuration>

9, The test results are as follows:

Keywords: Java Database Maven Mybatis

Added by dreamdelerium on Sat, 01 Jan 2022 09:29:39 +0200