Evolution from jdbc to mybatis

Posted by OriginalBoy on Fri, 22 Oct 2021 13:38:36 +0200

1. MyBatis and JDBC

1.1 introduction to MyBatis

MyBatis is an excellent persistence layer framework. It encapsulates the process of jdbc operating the database, so that developers only need to pay attention to SQL itself, and do not need to spend energy to deal with complicated jdbc process codes such as registering drivers, creating connection s, creating statement s, manually setting parameters, result set retrieval and so on.
Mybatis configures various statements (statement, preparedStatemnt, CallableStatement) to be executed through xml or annotation, and maps java objects and sql in the statement to generate the final executed sql statement. Finally, the mybatis framework executes sql, maps the results into java objects and returns them.

1.2 problems and improvements in JDBC development

     1: The frequent creation and release of database links cause a waste of system resources, which affects the system performance. For the acquisition and closing of MyBatis database connection, we can use database connection pool to solve the problem of resource waste. Through the connection pool, you can repeatedly use the established connections to access the database. Reduce the opening and closing time of the connection.

     2: SQL statements are hard coded in the code, which makes the code difficult to maintain. The actual application of SQL may change greatly. SQL changes need to change the java code. Mybatis writes SQL statements in the configuration file, and uses xml or annotations to execute various statements (statements
preparedStatemnt and CallableStatement) are configured, and the final executed SQL statement is generated by mapping java objects and SQL in the statement. Finally, the MySQL framework executes SQL, maps the results into java objects and returns them. In this way, when you need to change SQL, you only need to change the configuration file. (without affecting the interface)

     3: There is hard coding when using preparedStatement to transfer parameters to occupancy symbols, because the where conditions of sql statements are not necessarily, there may be more or less, and the code must be modified when modifying sql, so the system is not easy to maintain.

     4: There is hard coding (query column name) for result set parsing. The change of sql leads to the change of parsing code, which is difficult to maintain. It is more convenient to parse if the database records can be encapsulated into pojo objects. The Mapped Statement defines the output results of sql execution, including HashMap, basic type and pojo. The Executor uses the
The Mapped Statement maps the output result to the java object after executing sql. The mapping process of the output result is equivalent to the parsing process of the result in jdbc programming.

2. Create project test Mybatis

2.1. Establish a new database

     As shown in the figure

2.2. Create project

     Select new project

     Select Spring, and then next

     Naming, next

     Select Spring Web in Web and select the three items circled in SQL


Next, find completes the creation

2.3. Build the project file and complete the connection

     Create four packages and corresponding classes in the mybatis directory

UsreController

package com.example.databasedemo.controller;

import com.example.databasedemo.entity.Student;
import com.example.databasedemo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/Student") 
class UserController {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/getAllStudent")
    public List<Student> findAll(){
        return studentService.findAllStudent();
    }

    @RequestMapping("/getStudentByno/{no}")
    public List<Student> findUserByStudentId(@PathVariable int no){
        return studentService.findStudentByno(no);
    }
}


Student

package com.example.databasedemo.entity;

public class Student {
    private int no;
    private String name;
    private int age;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

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

    public String getName() {
        return name;
    }

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

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

}



StudentMapper

package com.example.databasedemo.mapper;

import com.example.databasedemo.entity.Student;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface StudentMapper {
    public List<Student> findAllStudent();

    List<Student> findStudentByno(int no);
}



StudentService

package com.example.databasedemo.service;
import com.example.databasedemo.entity.Student;
import com.example.databasedemo.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class StudentService {
    @Autowired(required = false)
    public StudentMapper studentMapper;
    public List<Student> findAllStudent() {
        return studentMapper.findAllStudent();
    }

    public List<Student> findStudentByno(int no) {
        return studentMapper.findStudentByno(no);
    }
}




     code: Code URL

     Operation results

     Web effect

3. Summary

There are still some differences between jdbc and mybatis. You need to import a jar package to use jdbc, but mybatis does not need to set all the configurations at the beginning. You can modify the configuration version at any time according to your own needs. The sql statement is separated from the code, and you can change the sql directly in the mapping file. When the database changes frequently or the query requirements change, The use of mybatis is more conducive to code maintenance.

Reference link: https://blog.csdn.net/weixin_46129506/article/details/120776483
https://blog.csdn.net/junseven164/article/details/120722181?spm=1001.2014.3001.5501

Topics: Java Database