MyBatis framework quick start

1. Preparatory work

Download mybatis: https://github.com/mybatis/mybatis-3/releases

Download mysql driver: https://mvnrepository.com/artifact/mysql/mysql-connector-java

Here I use the latest version of mybatis-3.5.9 and mysql-connector-java-8.0.22 jar.

2. Build development environment

(1) Create mysql database and tables

Database name: spring_db; Table name: student

CREATE TABLE `student` (
 `id` int(11) NOT NULL ,
 `name` varchar(255) DEFAULT NULL,
 `email` varchar(255) DEFAULT NULL,
 `age` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

(2) Create maven project

Under the empty project, create a new module

 

Because we only operate the database without any web application, we can create an ordinary javase project quickstart.

Tip: set to auto import dependency mode and wait for the project to build.

 

The project directory structure is as follows:

If the resources folder does not exist, you can create it yourself. In addition, the java folder is not blue. You need to right-click it and select Mark Directory as - "Sources Root".

 

(3) add dependency

<!--    mybatis rely on  -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>
<!--    mysql Drive dependency-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.22</version>
    </dependency>

Note the version correspondence.

If the dependency download fails, try to use the manual import method instead (right click pom.xml - "Maven -" Reimport).

 

3. Write entity class

Delete the App class generated by default before writing.

Package name: org.org example. domain; Class name: Student

// The recommended class name is the same as the table name, which is convenient for memory
public class Student {
    //Define attribute (requirement: the attribute name is the same as the column name)
    private Integer id;
    private String name;
    private String email;
    private Integer age;
    // ......
    // The set, get and toString methods are omitted below
}

4. Write Dao interface

This is the dao interface file of the persistence layer, which defines the relevant methods of operating the database.

Package name: org.org example. dao; Interface name: StudentDao

public interface StudentDao {

//    Query all data in student table
   public List<Student> selectStudents();

/**
The same applies to the interface of addition, deletion and modification
*/
}

5. Write Mapping SQL mapping file

It is used to write sql statements. Generally, a table is equipped with a mapping file (. xml), and mybatis will execute automatically.

Preparation requirements: (1) the same directory as the interface (dao); (2) The file name is consistent with the interface.

Click New File to create studentdao XML, 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="org.example.dao.StudentDao">

    <select id="selectStudents" resultType="org.example.domain.Student">
        select id,name,email,age from student
    </select>
</mapper>

explain:

  • Specifies the constraint file. mybatis-3-mapper.dtd is a constraint file, which is used to restrict and check whether the labels and attributes in the current file meet the configuration requirements of mybatis.
  • mapper: the root label of the current file (required).
  • Namespace: namespace with unique value. It can be customized. It is recommended to use the full class name of dao interface.
  • < Select >: query data. The tag must be a select statement.
  • id: the custom name of the sql statement. It is recommended to use the method name in dao interface.
  • resultType: the data type (ResultSet) of the result returned by the query statement, using the fully qualified class name.

6. Create master profile

In the src/main/resources directory (make sure the directory is resources root), create mybatis xml. The main configuration file name can be customized 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>
    <!--to configure mybatis environment-->
    <environments default="mysql">
        <!--id:Name of the data source-->
        <environment id="mysql">
            <!--Configuring transaction types: Using JDBC affair-->
            <transactionManager type="JDBC"/> 
            <dataSource type="POOLED">
                <!--Four elements of connecting database-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306 / database name "/ >
                <property name="username" value="User name to connect to the database"/>
                <property name="password" value="Password to connect to the database"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--appoint mybatis To execute sql Position of the statement-->
        <mapper resource="org/example/dao/StudentDao.xml"/>
    </mappers>
</configuration>

There are two corresponding values of name="driver". If your MySQL driver version is 5 x. Then the value value should be "com.mysql.jdbc.Driver", while the above "com.mysql.cj.jdbc.Driver" is mysql8 X-driven writing.

In the mapper tag, the value of the resource attribute is the path of the xml file in the same directory as the dao interface written in the previous sql statement, which can be quickly obtained in the following way:

Right click the file and select Copy Path.

Note: POM Add maven plugin to XML:

    <!-- scanning src/main/java Directory.properties,.xml file-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>

Because by default, maven will not scan the configuration files in the src/java directory. Remember to recompile to make sure there is no problem.

7. Create test class

Package name: org.org example; Class name: MyBatisTest

public static void main(String[] args) throws IOException {
        //1. Name of mybatis main configuration file
        String config = "mybatis.xml";
        //2. Read the configuration file
        InputStream in = Resources.getResourceAsStream(config);
        //3. Create SqlSessionFactoryBuilder object
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4. Create SqlSessionFactory object
        SqlSessionFactory factory = builder.build(in);
        //5. Obtain the SqlSession object and execute the sql statement
        SqlSession session = factory.openSession();
        //6. Specify the sql statement ID to be executed (consisting of namespace+ '.' +id in the sql mapping file)
        String sqlId = "org.example.dao.StudentDao" + '.' + "selectStudents";
        //7. Execute sql statement through sqlId
        List<Student> studentList = session.selectList(sqlId);

        //8. Circular output of query results
        studentList.forEach( student -> System.out.println(student));
        //9. Close SqlSession and release resources
        session.close();
    }

Tips:

(1) If the lambda expression is thrown red, check whether the Java compiled version is too low and adjust it to java8 version.

(2) If the database time zone problem is reported, add "? Servertimezone = UTC" after the url value in the main configuration file.

If there are no other problems, the operation result should be as follows:

Successfully read out the data in the student table. Well, so far, a simple and tortuous introduction case of mybatis operation database has been completed. After a long morning, my stomach growled and went to dinner first. If you have any questions, leave a message in the comment area and I will try my best to solve them.

Reference documents: http://mybatis.org/spring/zh/index.html

 

Keywords: Java Database Mybatis intellij-idea

Added by Frozenlight777 on Fri, 28 Jan 2022 02:27:03 +0200