首页 > 其他分享 >springboot整合mybatis实现简单的crud操作

springboot整合mybatis实现简单的crud操作

时间:2023-05-28 19:34:18浏览次数:49  
标签:return springboot int crud student Student mybatis import id

使用MyBatis框架操作数据,在SpringBoot框架集成MyBatis,项目整体结构
img
前提:准备一张student表。


SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int NOT NULL COMMENT '主键',
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '姓名',
  `age` int DEFAULT NULL COMMENT '年龄',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- ----------------------------
-- Records of user
-- ----------------------------
BEGIN;
INSERT INTO `student` (`id`, `name`, `age`) VALUES (1, '小强', 20);
INSERT INTO `student` (`id`, `name`, `age`) VALUES (2, '小刚', 27);
INSERT INTO `student` (`id`, `name`, `age`) VALUES (3, '小红', 22);
COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

使用步骤:

  1. 新建模块springboot-005-mybatis, 加入spring web, mybatis framework,mysql driver。其中mybatis起步依赖:完成mybatis对象自动配置,对象放在容器中.
    img
  2. pom.xml中加入resource插件, 把src/main/java目录中的**/*.xml文件包含到classpath中,表示把src/main/java目录下任意一个目录下面的*.xml文件包含道resources中;
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ben</groupId>
    <artifactId>springboot-005-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-005-mybatis</name>
    <description>springboot-005-mybatis</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--  mybatis起步依赖   -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.1</version>
        </dependency>
        <!--  mysql 驱动    -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <!--resources插件-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

  1. 写application.yml文件,配置数据库的连接信息。
server:
  port: 8080

# mysql驱动
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/spring6?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
  # 开启支持put delete请求的过滤器,false的时候,delete/put请求执行不生效;
  mvc:
    hiddenmethod:
      filter:
        enabled: true
#指定mapper文件的位置
mybatis:
  mapper-locations: classpath:mapper/*.xml
#指定mybatis的日志
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  1. 创建实体类Student
package com.ben.model;

/**
 * @Author: benjieqiang
 * @CreateTime: 2023-05-27  21:24
 * @Description: TODO
 * @Version: 1.0
 */
public class Student {
    private Integer id;
    private String name;
    private Integer age;

    public Student(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    // ... getter and setter, toString
}
  1. 创建Dao接口 StudentMapper , 创建一个查询所有学生的方法
package com.ben.dao;

import com.ben.model.Student;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @InterfaceName: StudentDao
 * @Description: 使用Mapper注解,让springboot找到接口和他的xml 文件,创建实现类对象, 位置:在接口的上面
 * @Author: benjieqiang
 * @LastChangeDate: 2023/5/27 9:25 PM
 * @Version: v1.0
 */

@Mapper
public interface StudentMapper {


    /**
     * @param student:
     * @return int
     * @description 插入新纪录
     * @author benjieqiang
     * @date 2023/5/28 5:41 PM
     */
    int insert(Student student);

    /**
     * @param student:
     * @return int
     * @description 根据其他进行插入
     * @author benjieqiang
     * @date 2023/5/28 5:46 PM
     */
    int insertSelective(Student student);

    /**
     * @param id: 主键
     * @return int
     * @description 根据id删除
     * @author benjieqiang
     * @date 2023/5/28 5:39 PM
     */
    int deleteById(Integer id);

    /**
     * @param id:
     * @return int
     * @description 根据主键更新
     * @author benjieqiang
     * @date 2023/5/28 5:42 PM
     */
    int updateById(Integer id);

    /**
     * @param student:
     * @return int
     * @description 根据其他更新
     * @author benjieqiang
     * @date 2023/5/28 5:45 PM
     */
    int updateBySelective(Student student);
    /**
     * @param id:
     * @return Student
     * @description 根据id查询
     * @author benjieqiang
     * @date 2023/5/28 5:21 PM
     */
    Student selectById(Integer id);
    /**
     * @param :
     * @return List<Student>
     * @description 查询所有学生
     * @author benjieqiang
     * @date 2023/5/27 9:25 PM
     */
    List<Student> selectAll();
}
  1. 在resources文件夹下面新建mapper目录,创建Dao接口对应的Mapper文件, StudentMapper.xml文件, 写sql语句
<?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.ben.dao.StudentMapper">
    <insert id="insert" parameterType="com.ben.model.Student" useGeneratedKeys="true">
        insert into student (id, name, age) values (null, #{name}, #{age})
    </insert>
    <delete id="deleteById" parameterType="java.lang.Integer">
        delete from student
        where id = #{id,jdbcType=INTEGER}
    </delete>

    <update id="updateById" parameterType="java.lang.Integer">
        update student
        set name = #{name},
            age = #{age}
        where id = #{id}
    </update>
    <select id="selectAll" resultType="com.ben.model.Student">
        select id,name,age from student
    </select>
    <select id="selectById" resultType="com.ben.model.Student">
        select id,name,age from student where id = #{id}
    </select>
</mapper>
  1. 创建Service层对象,创建StudentService接口和他的实现类StudentServiceImpl;
package com.ben.service;

import com.ben.model.Student;

import java.util.List;

/**
 * @Author: benjieqiang
 * @CreateTime: 2023-05-27  21:51
 * @Description: TODO
 * @Version: 1.0
 */
public interface StudentService {

    int insertStudent(Student student);

    int deleteStudentById(Integer id);

    int updateStudentById(Integer id);

    Student getStudentById(Integer id);
    List<Student> getAllStudents();
}
package com.ben.service.impl;

import com.ben.dao.StudentMapper;
import com.ben.model.Student;
import com.ben.service.StudentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: benjieqiang
 * @CreateTime: 2023-05-27  21:52
 * @Description: service实现类
 * @Version: 1.0
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper studentMapper;

    @Override
    public int insertStudent(Student student) {
        return studentMapper.insert(student);
    }


    @Override
    public int deleteStudentById(Integer id) {
        return studentMapper.deleteById(id);
    }

    @Override
    public int updateStudentById(Integer id) {
        return studentMapper.updateById(id);
    }

    @Override
    public Student getStudentById(Integer id) {
        return studentMapper.selectById(id);
    }

    @Override
    public List<Student> getAllStudents() {
        System.out.println("执行service中 getAllStudents方法");
        return studentMapper.selectAll();
    }
}
  1. 创建Controller对象,访问Service。
package com.ben.controller;

import com.ben.model.Student;
import com.ben.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: benjieqiang
 * @CreateTime: 2023-05-27  21:54
 * @Description: TODO
 * @Version: 1.0
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Resource
    private StudentService studentService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public String addStudent(Student student) {
        int count = studentService.insertStudent(student);
        return "add status:" + count;
    }


    //PathVariable 从url获取数据;
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public String deleteStudent(@PathVariable("id") Integer id) {
        int count = studentService.deleteStudentById(id);
        return "delete status: " + count;
    }


    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public String updateStudent(@PathVariable("id") Integer id) {
        System.out.println("执行update方法");
        int count = studentService.updateStudentById(id);
        return "update status:" + count;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") Integer id) {
        Student student = studentService.getStudentById(id);
        System.out.println(student);
        return student.toString();
    }
    @RequestMapping("/all")
    @ResponseBody
    public String getAllStudentsInfo() {
        List<Student> allStudents = studentService.getAllStudents();
        System.out.println(allStudents);

        return allStudents.toString();
    }
}
  1. 测试链接
    img

标签:return,springboot,int,crud,student,Student,mybatis,import,id
From: https://www.cnblogs.com/benjieqiang/p/17438709.html

相关文章

  • Mybatis-plus中自定义的sql语句调用QueryWrapper实现查询
     一、引言MP自带的条件构造器虽然很强大,有时候也避免不了写稍微复杂一点业务的sql,那么今天说说MP怎么自定义sql语句吧。 二、具体实现使用注解实现:在我们Mapper接口中定义自定义方法即可。/***@Date:2019/6/1014:40*@Description</span>:User对象持久层*/p......
  • springboot配置Swagger3.0
    springboot配置Swagger3.01、pom加入依赖我们创建一个SpringBoot项目,引入swagger3依赖<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency&......
  • mybatis plus 校验用户名是否重复
    添加//判断登录名的唯一性QueryWrapper<User>query=newQueryWrapper<>();query.lambda().eq(User::getLoginName,user.getLoginName());Userone=userService.getOne(query);if(one!=null&&one.getUserId()!=user.getUserId()){returnResult......
  • Java:mybatis-plus-generator-ui 基于Mybatis-Plus的代码自助生成器
    引用官方文档上的简介:提供交互式的WebUI用于生成兼容mybatis-plus框架的相关功能代码,包括Entity,Mapper,Mapper.xml,Service,Controller等,可以自定义模板以及各类输出参数,也可通过SQL查询语句直接生成代码。文档github:https://github.com/davidfantasy/mybatis-plus-generator-......
  • Java:SpringBoot整合Canal+RabbitMQ组合实现MySQL数据监听
    canal[kə’næl],译意为水道/管道/沟渠,主要用途是基于MySQL数据库增量日志解析,提供增量数据订阅和消费目录一、MySQL设置二、启动Canal服务端三、通过Canal客户端消费数据四、通过RabbitMQ消费数据1、启动RabbitMQ2、修改canal配置3、消费RabbitMQ中的数据文档资料github:https......
  • SpringBoot项目启动失败报错Annotation-specified bean name ‘xx‘ for bean class [
    Annotation-specifiedbeanname'datahubServiceImpl'forbeanclass[com.peony.common.service.impl.DatahubServiceImpl]conflictswithexisting,non-compatiblebeandefinitionofsamenameandclass[com.peony.common.service.DatahubServiceImpl] 1、......
  • MyBatis之返回值处理
    MyBatis之返回值处理1、返回值为基本数据类型当我们的SQL语句执行结束,要返回的类型为基本数据类型的时候,直接写你要返回的类型即可<insertid="addUser"parameterType="com.liu.pojo.User">insertintotb_uservalues(null,#{username},#{password});</insert>......
  • 使用纯Servlet完成单表的CRUD操作
    1. 使用纯粹的Servlet完成单表【对部门的】的增删改查操作。(B/S结构的。)   262. 实现步骤2.1 第一步:准备一张数据库表。(sql脚本)代码在E:\java\course14\CRUD  注意这里我们添加表的方式是dos窗口命令,使用命令source  E:\java\course14\CRUD  路径尽量不要有中文dept.sq......
  • Elasticsearch掰开揉碎第17篇SpringBoot集成Elasticsearch之索引操作
    引言上一篇主要讲解的是:高亮显示、自定义高亮显示、通过html展示高亮效果。本篇主要讲解的是:创建SpringBoot项目、SpringBoot项目的配置修改、创建配置类、索引的API操作。创建spring项目双击IntelliJIDEA工具创建配置类编辑测试类1、创建索引运行测试类运行结果查看现有的索引可......
  • Elasticsearch掰开揉碎第18篇SpringBoot集成Elasticsearch之文档操作
    引言上一篇主要讲解的是:创建SpringBoot项目、SpringBoot项目的配置修改、创建配置类、索引的API操作本篇主要讲解的是:文档的API操作(创建pojo、导入fastjosn依赖、添加文档、获取文档、获取文档信息、更新文档信息、删除文档信息、批量插入数据、高级查询)本篇文中所有操作,接着在上......