MyBatis02 -- getting started

1, Introductory case

MyBatis development preparation
Build MyBatis development environment and realize the first case

1. Prepare with Mybatis

download mybatis

2. Build MyBatis development environment

1) Create MySQL database and tables

Database name ssm; Table name student

Create table statement

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

Create maven project:

3) Add Maven coordinates

pom. Add maven coordinates to XML:

	<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency> 

4) Add Maven plugin

	<resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>

5) Write Student class

Create package com suyv. mybatis. Domain, create the Student class in the package

package com.suyv.mybatis.domain;

public class Student {
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    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 getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

6) Write Dao interface StudentDao

Create com suyv,mybatis. Dao package, create StudentDao interface

package com.suyv.mybatis.dao;

import com.suyv.mybatis.domain.Student;
import java.util.List;

public interface StudentDao {
    //Query all student data
    public List<Student> selectStudents();

}

7) Write Dao interface Mapper mapping file studentdao xml

matters needing attention:

  1. Create the file studentdao. In the dao package xml
  2. To StudentDao The XML file name is the same as the interface StudentDao, which is case sensitive.
<?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">
<!--
 namespace: Must have a value, a unique custom string 
 Recommended: dao Fully qualified name of the interface
-->
<mapper namespace="com.suyv.mybatis.dao.StudentDao">
    <!--
    <select>: Query data, the label must be select sentence
    id: sql The user-defined name of the statement, which is recommended dao Method name in the interface,
    Use a name to indicate what to do sql sentence
    resultType: The data type of the returned result of the query statement, using the fully qualified class name
    -->
    <select id="selectStudents" resultType="com.suyv.mybatis.domain.Student">
        <!--To execute sql sentence-->
        select id,name,email,age from student
    </select>
</mapper>

8) Create MyBatis master profile

Create the resources directory under project src/main, and set the resources directory to resources root

Create the main configuration file: the name is mybatis xml
Note: the name of the main configuration file is user-defined, and the contents are 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 Transaction (use) Connection (commit and rollback of)-->
            <transactionManager type="JDBC"/>
            <!--data source dataSource: Create database Connection object
            type: POOLED Connection pool using database
            -->
            <dataSource type="POOLED">
                <!--Four elements of connecting to a database-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--tell mybatis To execute sql Position of the statement-->
        <mapper resource="com/suyv/mybatis/dao/StudentDao.xml"/>
    </mappers>
</configuration>

9) Create test class MyBatisTest

src/test/java/com/suyv/mybatis/test / create mybatistest Java file

package com.suyv.mybatis.test;

import com.suyv.mybatis.domain.Student;
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 org.junit.Test;

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

public class MyBatisTest {

    @Test
    public void selectTest() throws IOException {
        //1.mybatis master configuration file
        String config = "mybatis.xml";
        //2. Read the configuration file
        InputStream in = Resources.getResourceAsStream(config);
        //3. Create SqlSessionFactoryBuilder object to obtain SqlSession
        SqlSessionFactoryBuilder bulider = new SqlSessionFactoryBuilder();
        //4. Create SqlSessionFactory object
        SqlSessionFactory factory = bulider.build(in);
        //5. [important] obtain the SqlSession object, and obtain the SqlSession from the SqlSessionFactory
        SqlSession sqlSession = factory.openSession();
        //6. Execute sql statement
        List<Student> studentList = sqlSession.selectList("com.suyv.mybatis.dao.StudentDao"+"."+"selectStudents");
        //7. Output results
        studentList.forEach(stu -> System.out.println(stu));
        //8. Close SqlSession and release resources
        sqlSession.close();
    }
}

10) Execution results

2, Basic CURD

1.insert

1) Add method in StudentDao interface

public int insertStudent(Student student);

2)StudentDao. Adding sql statements to XML

<insert id="insertStudent">
        insert into student(id,name,email,age) values(#{id},#{name},#{email},#{age})
</insert>

3) Add test method

@Test
    public void insertTest() throws IOException {
        //1.mybatis master configuration file
        String config = "mybatis.xml";
        //2. Read the configuration file
        InputStream in = Resources.getResourceAsStream(config);
        //3. Create SqlSessionFactoryBuilder object to obtain SqlSession
        SqlSessionFactoryBuilder bulider = new SqlSessionFactoryBuilder();
        //4. Create SqlSessionFactory object
        SqlSessionFactory factory = bulider.build(in);
        //5. [important] obtain the SqlSession object, and obtain the SqlSession from the SqlSessionFactory
        SqlSession sqlSession = factory.openSession();
        //6. Execute sql statement and find the statement through sqlId
        Student student = new Student();
        student.setId(1003);
        student.setName("Guan Yu");
        student.setEmail("guanyv@163.com");
        student.setAge(35);
        int nums = sqlSession.insert("com.suyv.mybatis.dao.StudentDao"+"."+"insertStudent",student);
        //mybatis does not commit transactions by default, so you need to manually commit transactions after insert, delete and update operations
        sqlSession.commit();
        //8. Output results
        System.out.println("implement insert result:"+nums);
        //7. Close SqlSession and release resources
        sqlSession.close();
    }

4) Execution results

IDEA console output:

The database results show:

2.update

1) Add method in StudentDao interface

public int updataStudent(Student student);

2)StudentDao. Adding sql statements to XML

    <update id="updataStudent">
        update student set age = #{age} where id=#{id}
    </update>

3) Add test method

	@Test
    public void updateTest() throws IOException {
        String config = "mybatis.xml";
        InputStream in = Resources.getResourceAsStream(config);
        SqlSessionFactoryBuilder bulider = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = bulider.build(in);
        SqlSession sqlSession = factory.openSession();
        Student student = new Student();
        student.setId(1003);
        student.setAge(25);
        int nums = sqlSession.update("com.suyv.mybatis.dao.StudentDao"+"."+"updataStudent",student);
        sqlSession.commit();
        System.out.println("implement insert result:"+nums);
        sqlSession.close();
    }

4) Execution results

IDEA console:

Database display results:

3.delete

1) Add method in StudentDao interface

public int deleteStudent(int id);

2)StudentDao. Adding sql statements to XML

    <delete id="deleteStudent">
        delete from student where id=#{id}
    </delete>

3) Add test method

@Test
    public void deleteTest() throws IOException {
        String config = "mybatis.xml";
        InputStream in = Resources.getResourceAsStream(config);
        SqlSessionFactoryBuilder bulider = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = bulider.build(in);
        SqlSession sqlSession = factory.openSession();
        int id = 1003;
        int nums = sqlSession.delete("com.suyv.mybatis.dao.StudentDao"+"."+"deleteStudent",id);
        sqlSession.commit();
        System.out.println("implement delete result:"+nums);
        sqlSession.close();
    }

4) Execution results

IDEA console:

Database display results:

3, MyBatis object analysis

1. Object usage

1) Resources class

The Resources class, as its name suggests, is a resource used to read resource files. There are many methods to return different types of IO stream objects by loading and parsing resource files.

2) Sqlsessionfactorybuilder class

The creation of SqlSessionFactory requires the use of the SqlSessionFactoryBuilder object
build() method. Because SqlSessionFactoryBuilder
After creating the factory object, the object completes its historical mission and can be destroyed. Therefore, the SqlSessionFactoryBuilder is generally used
The object is created as a local object within a method. When the method ends, the object is destroyed.

3) SqlSessionFactory interface

The SqlSessionFactory interface object is a heavyweight object (an object with high system overhead) and thread safe, so an application only needs one such object. establish
SqlSession requires the openSession() method of the SqlSessionFactory interface.
Open session (true): create a SqlSession with automatic submission function
Open session (false): create a SqlSession without automatic submission function, which needs to be submitted manually
´éč openSession(): the same as openSession(false)

4) SqlSession interface

The SqlSession interface object is used to perform persistence operations. A SqlSession corresponds to a database session. A session starts with the creation of the SqlSession object and ends with the closing of the SqlSession object.
The SqlSession interface object is thread unsafe, so you need to call its close() method to close it immediately before the end of each database session. The session needs to be created again. SqlSession is created inside the method and closed after use.

2. Create a tool class

1) Create MyBatisUtil class

package com.suyv.mybatis.util;

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.InputStream;

public class MybatisUtil {
    //Define SqlSessionFactory
    private static SqlSessionFactory factory = null;
    static {
        //Create a SqlSessionFactory once using a static block
        try{
            String config = "mybatis.xml";
            //Read configuration file
            InputStream in = Resources.getResourceAsStream(config);
            //Create SqlSessionFactory object
            factory = new SqlSessionFactoryBuilder().build(in);
        }catch (Exception e){
            factory = null;
            e.printStackTrace();
        }
    }
    /* Get SqlSession object */
    public static SqlSession getSqlSession(){
        SqlSession session = null;
        if( factory != null){
            session = factory.openSession();
        }
        return session;
    }
}

2) Using the MybatisUtil class

@Test
    public void testUtils() throws IOException {
        SqlSession session = MybatisUtil.getSqlSession();
        List<Student> studentList = session.selectList(
                "com.suyv.mybatis.dao.StudentDao.selectStudents");
        studentList.forEach( student -> System.out.println(student));
        session.close();
    }

3) Execution results

Keywords: JavaEE Mybatis SSM

Added by cytech on Wed, 05 Jan 2022 13:16:12 +0200