SpringBoot integrates Mybatis to realize basic addition, deletion, modification and query

What is Mybatis?

Mybatis is an excellent java-based persistence layer framework. It encapsulates jdbc inside, so that developers only need to pay attention to the SQL statement itself, without spending energy on loading drivers, creating connections, creating statements and other complicated processes.

SpringBoot integrates Mybatis

Create a SpringBoot project and introduce maven dependencies

		<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- mybatis依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

Create a mapper folder in the resources directory

Create databases and data tables and corresponding entity classes

package com.mybatis.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

// 引入lombok,省略getter和setter
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    private Integer id;
    private String username;
    private String email;
}

Improve the configuration file application.yml

server.port:
  8080
spring:
  datasource:
    username: root
    password: 123456
    ## mysql8版本需要在以下url中配置时区,即serverTimezone
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    ## 使用默认的Hikari数据源
    type: com.zaxxer.hikari.HikariDataSource

mybatis:
  ## 映射的实体类所在位置
  type-aliases-package: com.mybatis.entity
  ## mapper文件存放路径
  mapperLocations: classpath:mapper/*.xml

Create a new UserMapper.xml file

Implement basic addition, deletion, modification and query operations in the mapper file

Note : Do not add a semicolon at the end of the SQL statement in such files, otherwise mybatis may make mistakes when splicing SQL statements

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapper.UserMapper"> <!-- 命名空间为DAO文件存放位置-->
		<!-- 添加用户-->
    <insert id="addUser">
        insert into t_user (id, username, email)
        values (#{id}, #{username}, #{email})
    </insert>
		<!-- 删除用户-->
    <delete id="delUser">
        delete from t_user where id = #{id}
    </delete>
		<!-- 更新用户-->
    <update id="updateUser">
        update t_user
        set username = #{username}, email = #{email}
        where id = #{id}
    </update>
		<!-- 根据ID查找用户-->
    <select id="findById">
        select * from t_user where id = #{id}
    </select>
		<!-- 获取所有用户-->
    <select id="findAllUsers">
        select * from t_user
    </select>

</mapper>

Define DAO, the method name should be the same as in Mapper

package com.mybatis.mapper;

import com.mybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {
    
    
    int addUser(User user);

    int updateUser(User user);

    int delUser(Integer id);

    User findById(Integer id);

    List<User> findAllUsers();
}

define interface

package com.mybatis.service;

import com.mybatis.entity.User;

import java.util.List;

public interface UserService {
    
    
    int addUser(User user);

    int updateUser(User user);

    int delUser(Integer id);

    User findById(Integer id);

    List<User> findAllUsers();
}

Define the interface implementation class

package com.mybatis.service.impl;

import com.mybatis.entity.User;
import com.mybatis.mapper.UserMapper;
import com.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public int addUser(User user) {
    
    
        return userMapper.addUser(user);
    }

    @Override
    public int updateUser(User user) {
    
    
        return userMapper.updateUser(user);
    }

    @Override
    public int delUser(Integer id) {
    
    
        return userMapper.delUser(id);
    }

    @Override
    public User findById(Integer id) {
    
    
        return userMapper.findById(id);
    }

    @Override
    public List<User> findAllUsers() {
    
    
        return userMapper.findAllUsers();
    }
}

Directory Structure

insert image description here

test

package com.mybatis;

import com.mybatis.entity.User;
import com.mybatis.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class MybatisApplicationTests {
    
    
    @Autowired
    private UserService userService;

    @Test
    void contextLoads() {
    
    
        User user = new User(1, "小明", "[email protected]");
        userService.addUser(user);
    }
}


The test is successful and the data has been displayed in the database

Guess you like

Origin blog.csdn.net/wzc3614/article/details/127504117