Spring Boot tutorial - Mybatis

1. What is Mybatis?

MyBatis is an excellent persistence framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and getting result sets. MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) as records in the database through simple XML or annotations.

2. Spring Boot integrates Mybatis

  • 2.1 introducing maven coordinates

    <!--springboot Parent project-->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
        <dependencies>
            <!--springboot frame web assembly-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>2.2.2.RELEASE</version>
            </dependency>
            <!--mybatis integration springboot assembly-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.0</version>
            </dependency>
            <!--mysql Database connection driver-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.18</version>
            </dependency>
            <!--lombok assembly-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.10</version>
            </dependency>
        </dependencies>
    
        <build>
            <!--springboot Of maven plug-in unit-->
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <compilerArgs>
                            <arg>-parameters</arg>
                        </compilerArgs>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
  • 2.2 coding

    • 2.2.1 create a directory structure as shown in the figure

      Remember that the paths of the two mapper files should be the same. After compilation, the mapping files and interface files of mybatis will be in the same directory.

    • 2.2.2 code writing

      • 2.2.2.1 create configuration file and startup class

        application.yml:

        butterflytri:
          databaseurl-port: 127.0.0.1:3306 # Database port
          database-name: student_db # Database name
        server:
          port: 8080 # Application port
          servlet:
            context-path: /butterflytri # Apply mapping
        spring:
          application:
            name: mybatis # apply name
          datasource:
            url: jdbc:mysql://${butterflytri.databaseurl-port}/${butterflytri.database-name}?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
            driver-class-name: com.mysql.jdbc.Driver
            username: root
            password: root
        mybatis:
          type-aliases-package: org.wjf.entity # entity alias
          mapper-locations: classpath:org/wjf/mapper/*Mapper.xml # mapper mapping package scan
        

        Startup class MybatisApplication.java :

        package org.butterflytri;
        
        import org.springframework.boot.SpringApplication;
        import org.springframework.boot.autoconfigure.SpringBootApplication;
        
        /**
         * @author: WJF
         * @date: 2020/5/16
         * @description: MybatisApplication
         */
        @SpringBootApplication
        public class MybatisApplication {
        
            public static void main(String[] args) {
                SpringApplication.run(MybatisApplication.class,args);
            }
        
        }
        
      • 2.2.2.2 create entity class Student

        Create under entity package Student.java Entity class.

        package org.butterflytri.entity;
        
        import lombok.Getter;
        import lombok.Setter;
        import lombok.ToString;
        
        import java.io.Serializable;
        
        /**
         * @author: WJF
         * @date: 2020/5/16
         * @description: Student
         */
        
        @ToString
        @Getter
        @Setter
        public class Student implements Serializable {
        
            private Long id;
        
            private String studentName;
        
            private String studentNo;
        
            private String sex;
        
            private Integer age;
        
        }
        
      • 2.2.2.3 write mybatis interface file

        Create under mapper package StudentMapper.java Interface.

        package org.butterflytri.mapper;
        
        import org.apache.ibatis.annotations.Mapper;
        import org.butterflytri.entity.Student;
        
        import java.util.List;
        
        /**
         * @author: WJF
         * @date: 2020/5/16
         * @description:
         */
        @Mapper
        public interface StudentMapper {
        
            /**
             * Query all student information
             * @return List<Student>
             */
            List<Student> findAll();
        
            /**
             * Query student information by id
             * @param id
             * @return Student
             */
            Student findOne(Long id);
        
            /**
             * Query student information through student ID
             * @param studentNo
             * @return Student
             */
            Student findByStudentNo(String studentNo);
        
        }
        
      • 2.2.2.4 create mybatis mapping file

        Create under mapper package StudentMapper.xml .

        <?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.butterflytri.mapper.StudentMapper">
            <sql id="propertyMapper">
                `ID` AS id,
                `STUDENT_NAME` AS studentName,
                `STUDENT_NO` AS studentNo,
                `SEX` AS sex,
                `AGE` AS age
            </sql>
            <select id="findAll" resultType="org.butterflytri.entity.Student">
                SELECT
                    <include refid="propertyMapper"></include>
                FROM
                    `t_student`
            </select>
            <select id="findOne" parameterType="java.lang.Long" resultType="org.butterflytri.entity.Student">
                SELECT
                    <include refid="propertyMapper"></include>
                FROM
                    `t_student`
                WHERE
                    `ID` = #{id}
            </select>
            <select id="findByStudentNo" parameterType="java.lang.String" resultType="org.butterflytri.entity.Student">
                SELECT
                    <include refid="propertyMapper"></include>
                FROM
                    `t_student`
                WHERE
                    `STUDENT_NO` = #{studentNo}
            </select>
        </mapper>
        
      • 2.2.2.5 Service layer

        Create under service package StudentService.java Interface, creating under the impl package StudentServiceImpl.Java Class and inherit StudentService.Java Interface.

        StudentService.java:

        package org.butterflytri.service;
        
        import org.butterflytri.entity.Student;
        
        import java.util.List;
        
        /**
         * @author: WJF
         * @date: 2020/5/16
         * @description: StudentService
         */
        
        public interface StudentService {
        
            public List<Student> findAll();
        
            public Student findOne(Long id);
        
            public Student findByStudentNo(String studentNo);
        }
        
        

        StudentServiceImpl.java:

        package org.butterflytri.service.impl;
        
        import org.butterflytri.entity.Student;
        import org.butterflytri.mapper.StudentMapper;
        import org.butterflytri.service.StudentService;
        import org.springframework.stereotype.Service;
        
        import javax.annotation.Resource;
        import java.util.List;
        
        /**
         * @author: WJF
         * @date: 2020/5/16
         * @description: StudentServiceImpl
         */
        @Service
        public class StudentServiceImpl implements StudentService {
        
            @Resource
            private StudentMapper studentMapper;
        
            @Override
            public List<Student> findAll() {
                return studentMapper.findAll();
            }
        
            @Override
            public Student findOne(Long id) {
                return studentMapper.findOne(id);
            }
        
            @Override
            public Student findByStudentNo(String studentNo) {
                return studentMapper.findByStudentNo(studentNo);
            }
        }
        
      • 2.2.2.6 Controller layer

        Create under the controller package StudentController.java Controller class.

        package org.butterflytri.controller;
        
        import org.butterflytri.entity.Student;
        import org.butterflytri.service.StudentService;
        import org.springframework.web.bind.annotation.RequestMapping;
        import org.springframework.web.bind.annotation.RestController;
        
        import javax.annotation.Resource;
        import java.util.List;
        
        /**
         * @author: WJF
         * @date: 2020/5/16
         * @description: StudentController
         */
        @RestController
        @RequestMapping("/student")
        public class StudentController {
        
            @Resource
            private StudentService studentService;
        
            @RequestMapping("/findAll")
            public List<Student> findAll() {
                return studentService.findAll();
            }
        
            @RequestMapping("/findOne")
            public Student findOne(Long id) {
                return studentService.findOne(id);
            }
        
            @RequestMapping("/findByStudentNo")
            public Student findByStudentNo(String studentNo) {
                return studentService.findByStudentNo(studentNo);
            }
        
        }
        
      • 2.2.2.7 start the project, access path

        Start the project and access three interfaces:

        findAll:

        findOne:

        findByStudentNo:

3. Project address

Portal of the project: spring-boot-mybatis

This tutorial will be updated all the time. If it's OK for bloggers to write, pay attention to it, and it's more convenient for them to learn next time.

Tags: Java Mybatis Spring Database

Posted on Wed, 20 May 2020 11:42:05 -0400 by HaVoC