SpringBoot整合Mybatis---初步实现增删改查

SpringBoot整合Mybatis—初步实现增删改查

准备工作

  1. 建库建表

    数据库名:think

    数据表名:department

    属性:int型 id, String型 departmentName
    在这里插入图片描述

  2. Springboot项目中导入Mybatis需要的依赖

<!-- MyBatis 所需要的依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

当然别忘了mysql连接池的依赖

3、配置数据库连接信息

可以在resources目录下的application.properties下配置,这里则使用application.yml文件配置,只是格式不同而已

spring:
  datasource:
    username: root
    password:
    #?serverTimezone=UTC解决时区的报错,还有如果数据库不同记得更改数据库名
    url: jdbc:mysql://localhost:3306/think?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

4、测试数据库是否连接成功

编写测试类测试

package com.xin.jdbctest;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootTest
class JdbcTestApplicationTests {

    @Autowired
    DataSource dataSource;//自动配置数据源
    @Test
    void contextLoads() throws SQLException {
        System.out.println(dataSource.getClass());
        System.out.println(dataSource.getConnection());
    }

}

如果测试运行不报错表示连接成功

配置Mybatis

1、先创建一个实体类department

​ 创建一个entity包,在包中创建department实体类

package com.xin.jdbctest.entity;

public class Department {
    private int id;
    private String departmentName;

    public Department() {
    }

    public Department(int id, String departmentName) {
        this.id = id;
        this.departmentName = departmentName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }
}
  1. 创建mapper包以及对应的 Mapper 接口,并且先写上增删改查的方法
package com.xin.jdbctest.mapper;

import com.xin.jdbctest.entity.Department;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;
//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface DepartmentMapper {
    // 获取所有部门信息
    List<Department> getDepartments();

    // 通过id获得部门
    Department getDepartment(Integer id);

    //增加一个部门
    int addDepartment(Department department);

    //通过id删除一个部门
    int deleteDepartment(Integer id);

    //提供id修改部门名字
    int updateDepartment(Department department);
}
  1. 创建对应的Mapper映射文件

    在resources目录下创建一个mybatis目录,在mybatis目录下创建一个DepartmentMapper.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接口DepartmentMapper-->
    <mapper namespace="com.xin.jdbctest.mapper.DepartmentMapper">
     
     <!--获取所有部门信息 -->
        <select id="getDepartments" resultType="Department">
           select * from department;
        </select>
        
     <!--通过id获得部门 -->
        <select id="getDepartment" resultType="Department" parameterType="int">
           select * from department where id = #{id};
        </select>
        
    <!--增加一个部门 -->
        <insert id="addDepartment" parameterType="Department">
            insert into department (id,departmentName) values (#{id},#{departmentName});
        </insert>
        
    <!--通过id删除一个部门 -->
        <delete id="deleteDepartment" parameterType="int">
            delete from department where id = #{id};
        </delete>
        
    <!--提供id修改部门名字 -->
        <update id="updateDepartment" parameterType="Department">
            update department set departmentName = #{departmentName} where id = #{id};
        </update>
    </mapper>
    
    1. SpringBoot整合Mybatis

    要整合Mybatis还需要在resources目录下的application.properties下配置,这里依然以yaml文件为例

    spring:
      datasource:
        username: root
        password:
        #?serverTimezone=UTC解决时区的报错
        url: jdbc:mysql://localhost:3306/think?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
    
    #新增配置
    #整合mybatis
    mybatis:
    	#注意和自己的目录结构保持一致
      type-aliases-package: com.xin.jdbctest.entity
      mapper-locations: classpath:mybatis/*.xml
    
    

    编写DepartmentController进行测试

    创建controller包,并在包内创建DepartmentController

    package com.xin.jdbctest.controller;
    
    import com.xin.jdbctest.entity.Department;
    import com.xin.jdbctest.mapper.DepartmentMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    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
    public class DepartmentController {
        @Autowired
        DepartmentMapper departmentMapper;
    
        // 查询全部部门
        @GetMapping("/getDepartments")
        public List<Department> getDepartments(){
            return departmentMapper.getDepartments();
        }
    
        // 查询全部部门
        @GetMapping("/getDepartment/{id}")
        public Department getDepartment(@PathVariable("id") Integer id){
            return departmentMapper.getDepartment(id);
        }
    
        // 查询全部部门
        @GetMapping("/addDepartment")
        public String addDepartment(Integer id,String departmentName){
            int _id = (int) id;
            Department department = new Department(_id,departmentName);
            departmentMapper.addDepartment(department);
            return "OK";
        }
    
        @RequestMapping("/delete")
        public String delete(Integer id){
            System.out.println(departmentMapper.deleteDepartment(id));
            return "OK";
        }
    
        @RequestMapping("/update")
        public String update(Integer id,String departmentName){
            Department department = new Department(id,departmentName);
            departmentMapper.updateDepartment(department);
            return "OK";
        }
    
    }
    
    

    可以用postman测试,也可以自己在地址中传入参数
    测试成功就完成了基本的增删改查操作

最终的目录结构:
在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,需要在后端环境中搭建好 Spring BootMyBatis Plus 的开发环境,可以使用 Maven 或 Gradle 等构建工具来引入所需的依赖。 接下来,需要创建一个数据表对应的 Java 实体类,并使用 MyBatis Plus 提供的注解来标识表名、主键、字段等信息。例如: ``` @Data @TableName("user") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; } ``` 然后,创建一个 Mapper 接口,继承自 MyBatis Plus 提供的 BaseMapper 接口,用于定义增删改查等基本操作。例如: ``` public interface UserMapper extends BaseMapper<User> { } ``` 在 Spring Boot 的配置文件中,配置数据库连接信息和 MyBatis Plus 相关配置,例如: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis-plus.configuration.map-underscore-to-camel-case=true ``` 最后,在 Spring Boot 中创建一个 Controller 类,定义对应的请求处理方法,例如: ``` @RestController @RequestMapping("/user") public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/{id}") public User getUserById(@PathVariable("id") Long id) { return userMapper.selectById(id); } @PostMapping("") public void createUser(@RequestBody User user) { userMapper.insert(user); } @PutMapping("/{id}") public void updateUser(@PathVariable("id") Long id, @RequestBody User user) { user.setId(id); userMapper.updateById(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable("id") Long id) { userMapper.deleteById(id); } } ``` 这样,就完成了 Vue 和 Spring Boot 整合 MyBatis Plus 做增删改查的基本流程。在前端中,可以使用 Axios 等 HTTP 请求库来调用后端的接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值