Mybatis developed by Spring Boot

Mybatis developed by Spring Boot

1. Mybatis

1. Basic information

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java POJOs (Plain Ordinary Java Objects, ordinary Java objects) into records in the database.

2. Background introduction

1. MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures and advanced mapping. MyBatis eliminates almost all manual setting of JDBC code and parameters and retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, and maps interfaces and Java POJOs (Plain Ordinary Java Objects, ordinary Java objects) into records in the database.
2. Each MyBatis application mainly uses an instance of SqlSessionFactory, and an instance of SqlSessionFactory can be obtained through SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can be obtained from an xml configuration file or an instance of a predefined configuration class.
3. It is very simple to construct a SqlSessionFactory instance with an xml file. It is recommended to use a classpath resource in this configuration, but you can use any Reader instance, including one created with a file path or url starting with file://. MyBatis has a utility class ----Resources, which has many methods to easily load resources from the class path and other locations.

3. Features

  1. Easy to learn: itself is small and simple. Without any third-party dependencies, the simplest installation only needs two jar files + configuration of several sql mapping files. Easy to learn, easy to use. Through the documentation and source code, you can fully grasp its design ideas and implementation.
  2. Flexible: mybatis does not impose any impact on the existing design of the application or database. SQL is written in xml, which is convenient for unified management and optimization. All requirements for operating the database can be met through sql statements.
  3. Uncoupling sql and program code: By providing a DAO layer, business logic and data access logic are separated, making the system design clearer, easier to maintain, and easier to unit test. The separation of sql and code improves maintainability.
  4. Provides mapping tags to support ORM field relationship mapping between objects and databases.
  5. Object-relational mapping tags are provided to support object-relational building and maintenance.
  6. Provide xml tags and support writing dynamic sql.

4. Functional Architecture

We divide the functional architecture of Mybatis into three layers:

1. API interface layer: the interface API provided for external use, and developers use these local APIs to manipulate the database. Once the interface layer receives the call request, it will call the data processing layer to complete the specific data processing.
2. Data processing layer: responsible for specific SQL lookup, SQL parsing, SQL execution and execution result mapping processing, etc. Its main purpose is to complete a database operation according to the call request.
3. Basic support layer: Responsible for the most basic functional support, including connection management, transaction management, configuration loading, and cache processing. These are common things, and they are extracted as the most basic components. Provide the most basic support for the upper data processing layer.
insert image description here

2. Introductory case – adding, deleting, modifying and checking

1. Open the database that has been created in the previous study, and open the last project

insert image description here
insert image description here

2. Import dependent packages in pom.xml

insert image description here

<!--		引入mybatis包-->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.2</version>
		</dependency>
<!--		引入mysql包-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.29</version>
		</dependency>

3. Create a new mappers folder under the resources folder

insert image description here

4. Configure the connection in application.properties, and change the database port, name, user name, password and package name to your own, otherwise you will not be able to connect to the database

insert image description here
insert image description here

#配置连接
#数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接地址
spring.datasource.url=jdbc:mysql://localhost:3307/springboot?characterEncoding=utf8&serverTimezone=UTC
# 用户名和密码
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.name=defaultDataSource

#mybatis配置 sql写到配置文件
#实体类包
mybatis.type-aliases-package=com.example.springbooot.pojo
# sql配置文件xml路径
mybatis.mapper-locations=classpath:mappers/*.xml
#日志输出路径
logging.level.com.example.springbooot=debug

5. Query the database

(1) Create a new PersonMapper interface in the dao layer

insert image description here

package com.example.springbooot.dao;

import com.example.springbooot.pojo.Person;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;
//mybatis dao层实现类写到配置文件中
@Mapper
public interface PersonMapper {
    
    
  public List<Person> findAllPerson();
}

(2) Create a new PersonMapper.xml under the mappers folder

insert image description here
insert image description here

<?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.example.springbooot.dao.PersonMapper">
<!--    id 接口中方法的名字 resultType返回值的类型  集合对象 可以省略集合-->
<select id="findAllPerson" resultType="com.example.springbooot.pojo.Person">
            select * from class
</select>
</mapper>

(3) Create a new PersonService interface in the service layer, create a new impl folder, and create a new PersonServiceImpl implementation class under the impl folder

insert image description here

package com.example.springbooot.service;

import com.example.springbooot.pojo.Person;

import java.util.List;

public interface PersonService {
    
    
    public List<Person> findAllPerson();
}

package com.example.springbooot.service.impl;

import com.example.springbooot.dao.PersonMapper;
import com.example.springbooot.pojo.Person;
import com.example.springbooot.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonServiceImpl implements PersonService {
    
    
    @Autowired
    PersonMapper personMapper;

    @Override
    public List<Person> findAllPerson(){
    
    
        return personMapper.findAllPerson();
    }
}

(4) Create a new PersonController class in the controller layer

insert image description here

package com.example.springbooot.controller;

import com.example.springbooot.pojo.Person;
import com.example.springbooot.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PersonController {
    
    
    @Autowired
    PersonService personService;
    @RequestMapping("personlist")
    public String personlist(Model model){
    
    
        model.addAttribute("personlist",personService.findAllPerson());
        return "personlist.html";
    }

}

(5) Create a new personlist.html under the templates folder

insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
    <tr>
        <td>用户id</td>
        <td>用户年龄</td>
        <td>用户姓名</td>
    </tr>
    <tr th:each="person:${personlist}">
        <td th:text="${person.id}">用户id</td>
        <td th:text="${person.age}">用户年龄</td>
        <td th:text="${person.name}">用户姓名</td>
    </tr>
</table>
</body>
</html>

(6) Click to run, the database data access is successful

insert image description here

6. Delete user

(1) Modify the PersonMappe interface class of the dao layer

insert image description here

public int deletePersonById(Integer id);

(2) Modify PersonMapper.xml

insert image description here

    <delete id="deletePersonById" parameterType="Integer">
        delete from class where id=#{id}
    </delete>

(3) Modify the PersonService interface class

insert image description here

public int deletePersonById(Integer id);

(4) Modify the PersonServiceImpl implementation class

insert image description here

    @Override
    public int deletePersonById(Integer id) {
    
    
        return personMapper.deletePersonById(id);
    }

(5) Modify perosnlist.xml

insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table border="1">
    <tr>
        <td>用户id</td>
        <td>用户年龄</td>
        <td>用户姓名</td>
        <td>删除</td>
    </tr>
    <tr th:each="person:${personlist}">
        <td th:text="${person.id}">用户id</td>
        <td th:text="${person.age}">用户年龄</td>
        <td th:text="${person.name}">用户姓名</td>
        <th>
            <a th:href="@{
     
     '/deletepersonbyid?id='+${person.id}}">删除用户</a>
        </th>
    </tr>
</table>
</body>
</html>

(6) Modify the PersonController class

insert image description here

    @RequestMapping("deletepersonbyid")
    public String deletePersonbyid(int id){
    
    
        personService.deletePersonById(id);
        return "redirect:/personlist";
    }

(7) Click Run to perform the delete operation, and the database will update the data synchronously

insert image description here
insert image description here
insert image description here

7. Add users

(1) Modify the PersonMapper interface class of the dao layer

insert image description here

 public int addPerson(Person person);

(2) Modify PersonMapper.xml

insert image description here

<!--&lt;!&ndash;如果参数是对象类型 对象类型可以省略&ndash;&gt;-->
    <insert id="addPerson" parameterType="com.example.springbooot.pojo.Person">
        insert into class(name,age) values (#{name},#{age})
    </insert>

(3) Modify the PersonService interface class

insert image description here

 public int addPerson(Person person);

(4) Modify the PersonServiceImpl implementation class

insert image description here

    @Override
    public int addPerson(Person person) {
    
    
        return personMapper.addPerson(person);
    }

(5) Create a new addPerson.html under the templates folder

insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>增加用户</h1>
<form th:action="@{/addpersoncommit}" method="post">
  <div>用户名:<input name="name"></div>
  <div>年龄:<input name="age"></div>
  <div><input type="submit" value="提交"></div>
</form>
</body>
</html>

(6) Modify the PersonController class

insert image description here

    @RequestMapping("addperson")
    public String addperson(){
    
    

        return "addPerson.html";
    }
    @RequestMapping("addpersoncommit")
    public String addpersoncommit(Person person){
    
    
        personService.addPerson(person);
        return "redirect:/personlist";
    }

(7) Click Run, visit the addperson path, enter the user name and password to add users to the perosnlist page

insert image description here

insert image description here

8. Update users

(1) Modify the PersonMapper interface class of the dao layer

insert image description here

public int updatePerson(Person person);

(2) Modify PersonMapper.xml

insert image description here

    <update id="updatePerson" parameterType="com.example.springboot2.pojo.Person">
        update class
        set name=#{name},age=#{age}
        where id=#{id}
    </update>

(3) Modify the PersonService interface class

insert image description here

public int updatePerson(Person person);

(4) Modify the PersonServiceImpl implementation class

insert image description here

    @Override
    public int updatePerson(Person person) {
    
    
        return personMapper.updatePerson(person);
    }

(5) Modify personlist.html

insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<a th:href="@{/addperson}">增加页面</a>
<table border="1">
    <tr>
        <td>用户id</td>
        <td>用户年龄</td>
        <td>用户姓名</td>
        <td>删除</td>
        <td>更新</td>
    </tr>
    <tr th:each="person:${personlist}">
        <td th:text="${person.id}">用户id</td>
        <td th:text="${person.age}">用户年龄</td>
        <td th:text="${person.name}">用户姓名</td>
        <th>
            <a th:href="@{
     
     '/deletepersonbyid?id='+${person.id}}">删除用户</a>
        </th>
        <th>
            <a th:href="@{/updateperson(id=${person.id},age=${person.age},name=${person.name})}">更新用户</a>
        </th>

    </tr>
</table>
</body>
</html>

(6) Create a new updateperson.html under the tmplates folder

insert image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>
  更新页面
</h1>
<form th:action="@{/updatepersoncommit}" method="post">
  <div>id:<input name="id" th:value="${id}"></div>
  <div>用户名:<input name="name" th:value="${name}"></div>
  <div>年龄:<input name="age" th:value="${age}"></div>
  <div><input type="submit" value="提交"></div>
</form>
</body>
</html>

(7) Modify the PersonController class

insert image description here

    @RequestMapping("updateperson")
    public String updateperson(Model model,Person person){
    
    
        model.addAttribute("id",person.getId());
        model.addAttribute("age",person.getAge());
        model.addAttribute("name",person.getName());
        return "updateperson.html";
    }

    @RequestMapping("updatepersoncommit")
    public String updatepersoncommit(Person person){
    
    
        personService.updatePerson(person);
        return "redirect:/personlist";
    }

(8) Click to run, you can update the user operation

insert image description here
insert image description here
insert image description here
insert image description here
Using Mybatis to connect to the database to add, delete, modify and check is basically realized.

9. The resultmap attribute: the database field and the entity class field are inconsistent, and manual configuration is performed

(1) Modify PersonMapper.xml

insert image description here

<!--多表   resultMap 数据库字段和实体类字段不一致 手工配置-->
    <select id="findAllPerson" resultMap="person">
        select * from class
    </select>
    <resultMap id="person" type="com.example.springboot2.pojo.Person">
<!--        id 配置组件 column 数据库中列名字  property 实体类字段名-->
        <id column="id" property="id"></id>
        <result column="age" property="age"></result>
        <result column="name" property="name"></result>
    </resultMap>

(2) Click to run, you can also add, delete, modify and check

insert image description here

3. Resource download

Download address: Mybatis developed by Spring Boot learns
from the excellent behavior of excellent people! ! !

Guess you like

Origin blog.csdn.net/qq_61963074/article/details/127326875