SpringBoot整合Mybatis实现基础增删改查

什么是Mybatis?

Mybatis是一款优秀的基于java的持久层框架,它内部封装了jdbc,使开发者只需要关注sql语句本身,而不需要花费精力去处理加载驱动、创建连接、创建statement等繁杂的过程。

SpringBoot整合Mybatis

创建SpringBoot项目并引入maven依赖

		<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>

在resources目录下创建mapper文件夹

创建数据库和数据表以及对应实体类

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;
}

完善配置文件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

新建UserMapper.xml文件

在mapper文件中实现基础增删改查操作

注意:此类文件中不要在SQL语句末尾加上分号,否则mybatis在拼接SQL语句时可能会出错

<?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>

定义DAO,方法名要与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();
}

定义接口

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();
}

定义接口实现类

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();
    }
}

目录结构

在这里插入图片描述

测试

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);
    }
}


测试成功,数据库中已显示数据

猜你喜欢

转载自blog.csdn.net/wzc3614/article/details/127504117