SpringBoot+Mybatis+CRUD项目

一、项目要求

  • 创建一个 SpringBoot 项目,项目名”week11_学号”;
  • 使用 Mybatis 框架,也可以时可用 MybatisPlus 框架;
  • 访问 myschool 数据库;对 student 表进行操作,向 student 插入自己的一条记录,自行设计完成 CRUD操作;
  • 创建相应的 Pojo 层、Mapper 层、Service 层、Controller 层;
  • 在各层中,创建针对 student 表操作的类或接口;
  • 对 stuentController 设置一级和二级对外访问虚拟路径;
  • 启动服务器,测试控制器中的方法,直接将 CRUD 操作结果在后台打印出来;
  • 将运行结果截图,保存在 word 文档中。

二、下载Postman接口测试工具

postman可以很好的模拟浏览器并向API发送Request请求,所以一起来下载一下…
Postman下载地址
请添加图片描述
下载好后,注册账户,就可以开始用了,具体使用方法后面测试时讲

三、实验内容

1、jsp技术

Jsp和serlvet是开发动态web的一门技术,特别擅长开发B/S架构的程序,jsp和html文件相似。但是,SpringBoot不推荐使用JSP,所以如果想在SpringBoot中使用JSP,需要自己做一些配置。

2、Servlet技术

Servlet本质上就是Java类,但要遵循Servlet规范进行编写,它的创建、调用、销毁都由Servlet容器进行管理(如Tomcat,Jetty, WebLogic Server, JBoss等)。

3、MVC框架

在企业级Web项目开发中,标准的三层架构包括:表现层、业务层、数据访问层(持久层)。三层架构中,每一层各司其职,其中:

  • 表现层(UI)
  • 业务层(Service)
  • 数据访问层(持久层)
    请添加图片描述

MVC

  • 模型(Model)
  • 控制器(Controller)
  • 视图(View)

4、页面向控制器传递参数

  • 基本类型和 String 类型
  • POJO 类型参数,即实体类
  • 数组,集合类型参数
  • json 格式数据 (非常重要!!!后面在postman里要选择json)

5、SpringMVC 中常用注解小结

@Controller
//作用:修饰类,一个类被它修饰,就成了控制器类,负责接收和处理 HTTP 请求,可以返回页面和数据;
@RestController (@Controller+@ResponseBody 的组合注解)
//作用:修饰类,一个类被它修饰,就成了控制器类,只返回给用户数据,默认将返回的对象数据转换为 json 格式

@RequestMapping
//作用:负责 URL 的路由映射,建立请求 URL 和处理请求方法之间的对应关系,可以修饰类或类中的方法
@RequestParam 
//作用:将请求参数绑定到控制器的方法参数上,接收的参数来自http请求体或请求的url的QueryString
@RequestBody
//该注解主要用来接收前端传递给后端的 json 字符串中的数据(请求体中的数据的)。
@PathVaraible
//作用:处理动态URL,URL的值可以作为控制器中处理方法的参数,主要用于RestFul风格中

四、完整代码

1、配置文件

application.yml
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/myschool?serverTimezone=Hongkong?characterEncoding=utf8&serverTimezone=GMT%2B8
    username: root
    password: 密码

mybatis:
  mapper-locations: classpath:com/exmaple/mapper/*.xml    #指定sql配置文件的位置
  type-aliases-package: com.example.pojo      #指定实体类所在的包名
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   #输出SQL命令
pom.xml
<?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.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>week11_20201000000</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>week11_20201000000</name>
    <description>week11_20201000000</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </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>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**.*</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2、代码

Student.java
package com.example.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor //自动生成无参构造函数
@AllArgsConstructor
public class Student {
    private Long id;
    private String sname;
    private String dept;
    private int age;
}

StudentMapper.java
package com.example.mapper;

import com.example.pojo.Student;

import java.util.List;
import java.util.Map;

public interface StudentMapper {
    //1
    public List<Student> getAllStudentMap();

    //2
    public Student getStudentById(Long id);

    //3更新用户信息
    public int updateStudentByDynam(Map<Object,Object> mp);

    //4
    public int addStudent(Student student);

    //5
    public int deleteStudentById(Long id);

}

StudentMapper.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 namespace="com.example.mapper.StudentMapper">

	<!--1	-->
	<select id="getAllStudentMap" resultType="Student">
		SELECT * FROM student
	</select>

	<!--2	-->
	<select id="getStudentById" resultType="Student" parameterType="Long">
		SELECT * FROM student WHERE id=#{0}
	</select>

	<!--3	-->
	<update id="updateStudentByDynam"  parameterType="Map">
		update student
		<set>
			<if test="sname!=null">
				sname=#{sname},
			</if>
			<if test="dept!=null">
				dept=#{dept},
			</if>
			<if test="age!=null">
				age=#{age},
			</if>
			id=#{id}
		</set>
		where id=#{id}
	</update>

	<!--4	-->
	<insert id="addStudent" parameterType="Student">
		INSERT INTO student SET sname=#{sname},dept=#{dept},age=#{age}
	</insert>

	<!--5	-->
	<delete id="deleteStudentById" parameterType="Long">
		DELETE FROM student
		where id=#{id}
	</delete>

</mapper>

StudentService.java
package com.example.service;

import com.example.pojo.Student;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public interface StudentService {

        //1
        public List<Student> getAllStudentMap();

        //2
        public Student getStudentById(Long id);

        //3更新用户信息
        public int updateStudentByDynam(Map<Object,Object> mp);

        //4
        public int addStudent(Student student);

        //5
        public int deleteStudentById(Long id);

}
StudentServiceImpl.java
package com.example.service.impl;


import com.example.mapper.StudentMapper;
import com.example.pojo.Student;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    //根据id查询
    @Override
    public Student getStudentById(Long id){
        return studentMapper.getStudentById(id);
    }

    //根据id修改用户信息
    @Override
    public int updateStudentByDynam(Map<Object,Object> mp) {
        return studentMapper.updateStudentByDynam(mp);
    }

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

    //查询用户
    public List<Student> getAllStudentMap() {
        return studentMapper.getAllStudentMap();
    }

    public int addStudent(Student student) {
        return studentMapper.addStudent(student);
    }
}
StudentController.java
package com.example.controller;

import com.example.pojo.Student;
import com.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/getAllStudent",method = RequestMethod.GET)
    public List<Student> getAllStudent(){
        List<Student> studentList = studentService.getAllStudentMap();
        System.out.println("test");
        return studentList;
    }


    @RequestMapping(value = "/findStudentById",method =RequestMethod.GET)
    public Student findStudentById(Long id) throws IOException {
        Student studentById = studentService.getStudentById(id);
        System.out.println(studentById);
        return studentById;

    }


    @RequestMapping(value = "/addStudent",method = RequestMethod.POST)
    public int addStudent(Student student) {
        System.out.print(student);
        int num=studentService.addStudent(student);
        System.out.println(num);
        return num;
    }


    @RequestMapping(value = "/updateStudentByDynam",method =RequestMethod.POST)
    public int updateStudentByDynam(@RequestBody Map<Object,Object> mp){
        System.out.println("mp: ");
        System.out.println(mp);
        int row = studentService.updateStudentByDynam(mp);
        System.out.println(row);
        return row;
    }

    @RequestMapping(value = "/deleteStudentById",method =RequestMethod.POST)
    public int deleteStudentById(Long id){
        System.out.println("id: "+id);
        return studentService.deleteStudentById(id);

    }
}

Week1120201000000Application.java
package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan(basePackages ="com.example.mapper")
public class Week1120201000000Application {

    public static void main(String[] args) {
        SpringApplication.run(Week1120201000000Application.class, args);
    }

}

五、运行结果

1、postman使用

选择+输入+Key
点击Send
查看运行结果
请添加图片描述

2、localhost:8080/student/getAllStudent

在这里插入图片描述
在这里插入图片描述

3、localhost:8080/student/findStudentById?id=20201001111

在这里插入图片描述

在这里插入图片描述

4、localhost:8080/student/addStudent?sname=addtest&dept=depttest&age=10

在这里插入图片描述
在这里插入图片描述
用getAllStudent()查一下
在这里插入图片描述

5、localhost:8080/student/updateStudentByDynam

{
    "id":20201005591,
    "sname": "updatetest",
    "dept": "updatetest"
}

在这里插入图片描述
在这里插入图片描述

6、localhost:8080/student/deleteStudentById?id=20201005564

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

最后,部分代码参考自大佬的软件工程综合实践课程第十一周作业( SpringBoot整合Mybatis完成CRUD操作并使用接口调试工具对接口进行测试)

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值