0
点赞
收藏
分享

微信扫一扫

Springboot之SpringMVC与MyBatis(一)

GhostInMatrix 2022-09-10 阅读 87

文章目录

MyBatis框架

  • 此框架是目前最流行的数据持久层框架,框架可以帮助我们生成JDBC代码,从而提高开发效率,使用此框架程序员需要通过注解或xml配置文件写好需要执行的SQL语句接口,MyBatis框架会自定生成对应的JDBC代码

如何使用MyBatis框架

1.创建SpringBoot工程

  • Web->Spring Web
  • SQL->MyBatis Framework
  • SQL->MySQL Driver
    在这里插入图片描述

2.创建工程后需要在application.properties配置文件中添加连接数据库的信息

spring.datasource.url=jdbc:mysql://localhost:3306/empdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

项目(1) 使用MyBatis代替JDBC迭代商品管理系统

创建SpringBoot工程加入SpringMVC和Mybatis(SQL Driver,MyBatis Frame)

代码结构

在这里插入图片描述

建表

CREATE TABLE product(id INT PRIMARY KEY AUTO_INCREMENT,title VARCHAR(50),
price DOUBLE(10,2),num INT);

前端页面(1)

主页index.index

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>商品管理系统</h1>
<a href="/insert.html">添加商品</a>
<a href="/select">商品列表</a>
<a href="/update.html">商品修改</a>
</body>
</html>

新增商品页面insert.html

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/insert">
    <input type="text" name="title" placeholder="商品标题">
    <input type="text" name="price" placeholder="商品价格">
    <input type="text" name="num" placeholder="商品库存">
    <input type="submit" value="添加商品">
</form>
</body>
</html>

修改商品页面update.html

在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>修改页面</h1>
<form action="/update">
    <input type="text" name="id" placeholder="请输入要修改的商品编号">
    <input type="text" name="title" placeholder="请输入商品名称">
    <input type="text" name="price" placeholder="请输入商品价格">
    <input type="text" name="num" placeholder="请输入库存数量">
    <input type="submit" value="提交">
</form>
</body>
</html>

后端代码(2)

实体类

package cn.tedu.boot03.entity;

public class Product {
    private Integer id;
    private String title;
    private Double price;
    private Integer num;

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", price=" + price +
                ", num=" + num +
                '}';
    }

    public Product() {
    }

    public Product(Integer id, String title, Double price, Integer num) {
        this.id = id;
        this.title = title;
        this.price = price;
        this.num = num;
    }

    //set,get省略

mapper

package cn.tedu.boot03.mapper;

import cn.tedu.boot03.entity.Product;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface ProductMapper {
    //#{变量名} 会自动找到下面方法中参数列表里面的同名参数,
    // 如果没有同名参数的话会调用参数列表中对象的getXXX方法
    @Insert("insert into product values(null,#{title},#{price},#{num})")
    void insert(Product product);

    //Select注解执行查询相关的SQL语句,查询到的数据会自动封装到Product对象中并且把
    //多个对象添加到list集合中
    @Select("select * from product")
    List<Product> select();

    @Delete("delete from product where id=#{id}")
    int deleteById(int id);
    @Update("update product set title=#{title},price=#{price},num=#{num} where id=#{id}")
    int update(Product product);
}

controller

package cn.tedu.boot03.controller;

import cn.tedu.boot03.entity.Product;
import cn.tedu.boot03.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProductController {
    //自动装配注解,此注解是Spring框架中提供的注解,添加此注解后Spring框架和MyBatis框架
    //会创建一个实现类(实现了ProductMapper接口),并且实例化了此实现类,把实例化后的对象赋值给了mapper变量
    @Autowired(required = false)//如果Autowired注解报错则添加(required=false) 解决误提示
    ProductMapper mapper;

    @RequestMapping("/insert")
    public String insert(Product product){
        System.out.println("product = " + product);
        mapper.insert(product);
        return "添加完成!<a href='/'>返回首页</a>";
    }

    @RequestMapping("/select")
    public String select(){
        List<Product> list = mapper.select();
        String html="<table border='1'>";
        html+="<caption>商品列表</caption>";
        html+="<tr><th>id</th><th>标题</th><th>价格</th><th>库存</th><th>操作</th></tr>";
        for(Product product:list){
            html+="<tr>";
            html+="<td>"+ product.getId()+"</td>";
            html+="<td>"+ product.getTitle()+"</td>";
            html+="<td>"+ product.getPrice()+"</td>";
            html+="<td>"+ product.getNum()+"</td>";
            html+="<td><a href='delete?id="+ product.getId()+"'>删除</a></td>";
            html+="</tr>";
        }
        html+="</table>";
        return html;
    }

    @RequestMapping("/delete")
    public String delete(int id){
        int count = mapper.deleteById(id);
        System.out.println("id = " + id);
        if(count>0){
            return "删除成功<a href='/select'>返回列表页面</a>";
        }
        return "删除失败<a href='/select'>返回列表页面</a>";
    }
    @RequestMapping("/update")
    public String update(Product product){
        int count=mapper.update(product);
        if (count>0){
            return "修改成功<a href='/'>返回主页面</a>";
        }
        return "修改失败<a href='/'>返回修改页面</a>";
    }
}

总结知识点

@Autowired(required = false)

自动装配注解,此注解是Spring框架中提供的注解,添加此注解后Spring框架和MyBatis框架
会创建一个实现类(实现了ProductMapper接口),并且实例化了此实现类,把实例化后的对象赋值给了mapper变量
@Autowired(required = false)//如果Autowired注解报错则添加(required=false) 解决误提示
ProductMapper mapper;

项目(2) 使用MyBatis代替JDBC迭代注册登录

代码结果

在这里插入图片描述

建表

CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(50),PASSWORD VARCHAR(50),nick VARCHAR(50),
)CHARSET=utf8;

前端页面(1)

主页index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>工程首页</h1>
<a href="/reg.html">注册</a>
<a href="/login.html">登录</a>
</body>
</html>

登录页面login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登录页面</h1>
<form action="/login">
    <input type="text" name="username" placeholder="请输入用户名">
    <input type="text" name="password" placeholder="请输入密码">
    <input type="submit" 登录>
</form>
</body>
</html>

注册页面reg.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>注册页面</h1>
<form action="/reg">
    <input type="text" name="username" placeholder="用户名">
    <input type="text" name="password" placeholder="密码">
    <input type="text" name="nick" placeholder="昵称">
    <input type="submit" value="注册">
</form>
</body>
</html>

后端代码(2)

实体类

public class User {
    private Integer id;
    private String username;
    private String password;
    private String nick;

    public User() {
    }

    public User(Integer id, String username, String password, String nick) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.nick = nick;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", nick=" + nick +
                '}';
	//省略get/set方法
    }

mapper接口

@Mapper
public interface UserMapper {
    @Select("select id,username,password,nick from user where username=#{username}")
    User selectByName(String username);

    @Insert("insert into user values(null,#{username},#{password},#{nick})")
    int insert(User user);
}

Controller

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/login")
    public String login(User user){
        System.out.println("user = " + user);
        User u = mapper.selectByName(user.getUsername());
        if(u!=null){
            if (u.getPassword().equals(user.getPassword())){
                return "登录成功";
            }
            return "密码错误";
        }
        return "用户名不存在";
    }
    @RequestMapping("/reg")
    public String reg(User user){
        System.out.println("user = " + user);
        //查询注册用户是否存在
        User u = mapper.selectByName(user.getUsername());
        if(u!=null){
            return "用户名存在";
        }
        int count=mapper.insert(user);
        if (count>0){
            return "注册成功";
        }
        return "注册失败";
    }
}
举报

相关推荐

0 条评论