先让SpringBoot、MyBatisPlus跑起来

架空一切前提条件,只讲怎么让它跑起来,实现基本的增删改查操作!
假设:
1、MySQL里已经有一张user表;
2、已经安装IDEA
3、已经新建一个SpringBoot项目;
4、已经部署好MyBatisPlus相关配置;

src/main/resources/application.yml配置例子:

spring:
  datasource:
                                              #    TODO : allowPublicKeyRetrieval=true
    url: jdbc:mysql://localhost:3306/user?useUnicode=true&allowPublicKeyRetrieval=true&useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

server:
  port: 8080

mybatis-plus:
  global-config:
    db-config:
      #  TODO : MyBatis-plus 设置 id 自增
      id-type: auto

src/main/java/tabkey9/dao/UserDao.java DAO层:

import tabkey9.entity.UserEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

/**
 * 用户信息表 - DAO 层
 *
 * @author TabKey9
 * @date 2022-3-25
 */
@Mapper
public interface UserDao extends BaseMapper<UserEntity> {

}

src/main/java/tabkey9/dao/UserDao.java 映射的实体类:

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;
import java.util.Date;
import lombok.Data; // 引入这个依赖就可以不用写 SET/GET

/**
 * 用户信息表 - 映射的实体类
 *
 * @author TabKey9
 * @date 2022-3-25
 */
@Data
@TableName("user")
public class UserEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 用户编号
	 */
	@TableId
	private Integer id;
	/**
	 * 用户姓名
	 */
	private String user;
	/**
	 * 年龄
	 */
	private Integer age;
	/**
	 * 性别
	 */
	private String sex;
	/**
	 * 手机号码
	 */
	private String phone;
	/**
	 * 注册时间
	 */
	private Date addDate;
	/**
	 * 密码
	 */
	private String password;

}

TODO: 前面都是部署,现在开始写业务代码,我的思路是:

1、先在 调用 写 调用的方法,IEDA报错没有该方法,不理它,根据报错,跳转去写 服务
2、写 服务IDEA又报错,没有该服务的实现,不理它,根据报错,跳转去写 实现
3、当调用服务实现都写了,IDEA还报错,就要去找原因了,最后再调试一下。

TODO:下面是一个 增删改查Demo,用了 MyBatisPlus 内置的 CRUD,简化了很多代码量

src/main/java/tabkey9/controller/UserController.java 调用:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tabkey9.entity.UserEntity;
import tabkey9.service.UserService;

import java.util.HashMap;
import java.util.List;


/**
 * 用户信息表 - 调用
 *
 * @author TabKey9
 * @date 2022-3-25
 */
@RestController
@RequestMapping("/user")
public class UserController {
//    @Resource
//    private UserDao mapper;
    @Autowired
    private UserService userService;

    // 根据主键 id 查询一条数据
    @GetMapping("/getId")
    public UserEntity getId(@RequestParam(required = false) Integer id){ // RequestParam加上(required = false)表示可以不传参数,看需求加
        Integer param = id == null ? 1 : id; // 用了三元运算符,不穿参数则默认查 id 为 1 的数据
        return userService.getId(param);
    }

    // 删除 ,根据指定“id"字段删除数据
    @RequestMapping("/delId")
    public boolean delId( @RequestParam(required = false) Integer id) {
        if (id==null) return false; // 防止报错
//        根据指定主键 ID 删除数据
        return userService.delId(id);
    }

    // 删除 ,根据指定“name"字段删除数据
    @RequestMapping("/delName")
    public boolean delName( @RequestParam String name) {
        if (name==null) return false; // 防止报错
        return userService.delName(name);
    }

    // 查询所有数据
    @GetMapping("/list")
//    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public List<UserEntity> lists(){
        return userService.lists();
    }

    // 增 一条,通过 前端传参 id 改变主键
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public boolean insertOne(@RequestParam HashMap<String, String> info) {
        UserEntity user = new UserEntity();
        user.setUser( info.get("user") );
        user.setAge( Integer.parseInt(info.get("age") ));
        user.setPhone( info.get("phone") );
        user.setSex( info.get("sex") );
        user.setPassword( info.get("password") );
        return userService.insOne(user);
    }

//    根据 id 修改一条数据
    @RequestMapping("/save")
    public boolean cUpdate() {
        UserEntity user = new UserEntity();
        user.setId(41); // 注意这三个字段在数据库中是不为空的,所有至少得加上这三个字段,其余不 set 的字段,默认不更新
        user.setUser("小小"); // DB 中不为空
        user.setPassword("admin"); // DB 中不为空
        return userService.cUpDate(user);
    }

}

src/main/java/tabkey9/service/UserService.java 服务:

import com.baomidou.mybatisplus.extension.service.IService;
import tabkey9.entity.UserEntity;

import java.util.List;

/**
 * 用户信息表 - 服务
 *
 * @author TabKey9
 * @date 2022-3-25
 */
public interface UserService extends IService<UserEntity> {

    // 根据 id 字段查
    UserEntity getId(Integer id);

    // 查询所有数据
    List<UserEntity> lists();

    // 根据 id 删除
    boolean delId(Integer id);

    boolean delName(String name);

    // 新增 1条
    boolean insOne(UserEntity user);

    // 更新
    boolean cUpDate(UserEntity user);
}

src/main/java/tabkey9/service/impl/UserServiceImpl.java 实现:

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import tabkey9.dao.UserDao;
import tabkey9.entity.UserEntity;
import tabkey9.service.UserService;

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

/**
 * 用户信息表 - 实现
 *
 * @author TabKey9
 * @date 2022-3-25
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Resource
    private UserDao mapper; // 相当于实例化了一个名为 mapper 的 UserDao 对象

//    指定 id 字段查
    @Override
    public UserEntity getId(Integer id) {
        return this.getById(id);
    }

//    查所有数据
    @Override
    public List<UserEntity> lists(){
        return this.list();
    }

//    指定 id 删除
    @Override
    public boolean delId(Integer id) {
        return this.removeById(id);
    }

//    指定 name 字段删除数据
    @Override
    public boolean delName(String name) {
//        不使用映射字段的话,就要自己指定字段名
//        this.remove(new QueryWrapper<UserEntity>().eq("user" ,"root") );
//        使用了链式查询【lambda()】,映射字段,方便开发
        return this.remove(new QueryWrapper<UserEntity>().lambda().eq(UserEntity::getUser,name));
    }

//    根据前端 HTML Form 表单传参进行数据处理,实例化 UserEntity 实例并 Set 值,最后再通过 DAO 层写入数据库
//    演示:  file:///C:/Users/EDY/Desktop/main/resources/html.html
    @Override
    public boolean insOne(UserEntity user) {
        return this.save(user);
    }

//    更新一条数据
    @Override
    public boolean cUpDate(UserEntity user) {
        return this.updateById(user);
    }

}

再来个简单的 HTML Form 表单:

<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div style="color: rgb(20, 169, 189); margin-left: 20px; margin-right: 20px; text-align:right; width:300px">
        <form name="info" accept-charset="UTF-8" action="http://localhost:8080/user/insert" method="post" ectype="application/json" >
            <fieldset>
                <legend>form表单 注册:</legend>
                姓名:<input style="width: 170px;" type="text" name="user" value="刘备">
                <br>
                年龄:<input type="text" name="age" value="25">
                <br>
                性别:<input type="text" name="sex" value="男">
                <br>
                手机:<input type="text" name="phone" value="18888888888">
                <br>
                密码:<input type="text" name="password" value="root">
                <br>
                <input type="submit" value="Submit">
            </fieldset>
        </form>
    </div>
</body>
</html>

TODO: 一边跑起来,一边理解这里为什么这样?那里为什么那样?,换成这样行不行?换成那样行不行?

扩展:附一张图:

posted @ 2022-03-25 18:46  TabKey9  阅读(75)  评论(2编辑  收藏  举报