适合初学者-sprungboot+mybatis实现增删改查

springboot初识

(适合初学)springboot+mybatis实现增删改查

前言

开发工具及版本:
window10
idea-2018.2.2
maven-3.54
navicat

效果图

适合初学者-sprungboot+mybatis实现增删改查_第1张图片适合初学者-sprungboot+mybatis实现增删改查_第2张图片
适合初学者-sprungboot+mybatis实现增删改查_第3张图片
适合初学者-sprungboot+mybatis实现增删改查_第4张图片

适合初学者-sprungboot+mybatis实现增删改查_第5张图片

目录结构

适合初学者-sprungboot+mybatis实现增删改查_第6张图片

springboot框架简介

数据库

demo数据库,表名users
适合初学者-sprungboot+mybatis实现增删改查_第7张图片

pom.xml

通过Maven导入,不知道怎么配置maven可以自行百度

<?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.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>mybits</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybits</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <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.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <!-- freemarker模板引擎视图 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

        <!-- 热部署,不用重启 ,这个在这里不需要-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <!-- jsp解析器 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

对于一个项目,从发起到响应流程

适合初学者-sprungboot+mybatis实现增删改查_第8张图片

controller层

Controller层:控制层 控制业务逻辑
具体的业务模块流程的控制,controller层主要调用Service层里面的接口控制具体的业务流程,控制的配置也要在配置文件中进行。

package com.example.mybits.Controller;

import com.example.mybits.Model.User;
import com.example.mybits.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import org.springframework.web.servlet.ModelAndView;

@Controller
//@RestController
public class UserController {

    @Autowired
    private UserService userService;

    //查询所有
    @RequestMapping("/selectUserAll")
    public ModelAndView selectUserAll(){
        ModelAndView mav = new ModelAndView("selectUserAll");
        mav.addObject("user", userService.selectUserAll());
        return mav;
    }

    //根据id查询用户
    @RequestMapping("/selectUserById")
    public ModelAndView selectUserById(Integer id){
        ModelAndView mav = new ModelAndView("selectUserById");
        mav.addObject("user",userService.selectUserById(id));
        return mav;

    }

    //根据number查询用户
    @RequestMapping("/selectUserByNumber")
    public ModelAndView selectUserByNumber(String number){
        ModelAndView mav = new ModelAndView("selectUserByNumber");
        mav.addObject("user",userService.selectUserByNumber(number));
        return mav;

    }

    //根据工号查询用户(name)
    @RequestMapping("/selectUserByName")
    public ModelAndView selectUserByName(String name){
        ModelAndView mav = new ModelAndView("selectUserByName");
        mav.addObject("user",userService.selectUserByName(name));
        return mav;

    }

    //根据id删除用户
    @RequestMapping("/deleteUserById")
    public String deleteUser(Integer id){
        userService.deleteUser(id);
        return "redirect:selectUserAll";
    }

    //添加用户
    @RequestMapping("/addUser")
    public String addUser(User user){
        userService.addUser(user);
        return "redirect:selectUserAll";
    }


    @RequestMapping("/add")
    public ModelAndView addController(User user){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("add");
        return mav;
    }

    //通过id显示修改内容
    @RequestMapping("/selectOneById")
    public ModelAndView selectOneById(int id){
        ModelAndView mav = new ModelAndView("update");
        mav.addObject("user", userService.selectOneById(id));
        return mav;
    }


    //根据id修改用户
    @RequestMapping("/updateUserById")
    public String updateUserById(User user){
        userService.updateUser(user);
        return "redirect:selectUserAll";
    }

}

dao层(持久层)

Dao层:持久层,主要是和数据库进行交互
dao层首先胡创建dao接口,接着就可以在配置文件中定义该接口的实现类;接着就可以在模块中调用dao的接口进行数据业务的处理,而不用关注此接口的具体实现是哪一个类,dao层的数据源和数据库实在配置文件中进行配置的。

UserDao接口:

package com.example.mybits.Dao;

import com.example.mybits.Model.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

//@Repository
@Mapper
public interface UserDao {
    void addUser(User user);
    void deleteUser(Integer id);
    void updateUser(User user);
    List<User> selectUserAll();
    List<User> selectUserById(int id);
    User selectOneById(Integer id);

    List<User> selectUserByNumber(String number);
    List<User> selectUserByName(String name);
}

Mapper——userMapper.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.mybits.Dao.UserDao">
    <sql id="table">users</sql>
    <resultMap id="BaseResultMap" type="com.example.mybits.Model.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="number" property="number" jdbcType="VARCHAR" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="local" property="local" jdbcType="VARCHAR" />
        <result column="ip" property="ip" jdbcType="VARCHAR" />
        <result column="note" property="note" jdbcType="VARCHAR" />
    </resultMap>

    <insert id="addUser" parameterType="com.example.mybits.Model.User" useGeneratedKeys="true" keyProperty="id">
        insert into users (id,number,name,local,ip,note) values (#{id}, #{number}, #{name}, #{local}, #{ip}, #{note})
    </insert>

    <delete id="deleteUser" parameterType="com.example.mybits.Model.User">
        delete from  users where id=#{id}
    </delete>

    <select id="selectUserAll" resultType="com.example.mybits.Model.User">
        select * from users
    </select>

    <select id="selectUserById" resultType="com.example.mybits.Model.User">
        select * from users where id like concat(concat('%',#{id}),'%');
    </select>


    <select id="selectOneById" resultType="com.example.mybits.Model.User">
        select * from users where id like concat(concat('%',#{id}),'%');
    </select>

    <select id="selectUserByNumber" resultType="com.example.mybits.Model.User">
        select * from users where number like concat(concat('%',#{number}),'%');
    </select>

    <select id="selectUserByName" resultType="com.example.mybits.Model.User">
        select * from users where name like concat(concat('%',#{name}),'%');
    </select>

    <update id="updateUser" parameterType="com.example.mybits.Model.User">
        update users set number=#{number}, name=#{name}, local=#{local}, ip=#{ip}, note=#{note} where id=#{id}
    </update>
</mapper>

Model层

Mode层也称为po层和Entity层:实体层,数据库在项目中的类
主要用于定义与数据库对象的属性,提供get/set方法,带参和无参的构造方法。

User:

package com.example.mybits.Model;


public class User {

  private Integer id;
  private String number;
  private String name;
  private String local;
  private String ip;
  private String note;


  public Integer getId() {
    return id;
  }

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


  public String getNumber() {
    return number;
  }

  public void setNumber(String number) {
    this.number = number;
  }


  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }


  public String getLocal() {
    return local;
  }

  public void setLocal(String local) {
    this.local = local;
  }


  public String getIp() {
    return ip;
  }

  public void setIp(String ip) {
    this.ip = ip;
  }


  public String getNote() {
    return note;
  }

  public void setNote(String note) {
    this.note = note;
  }

}

Service层

Service层:业务层控制业务
业务模块的逻辑应用设计,和DAO层一样都是先设计接口,再创建要实现的类,然后在配置文件中进行配置其实现的关联。接下来就可以在service层调用接口进行业务逻辑应用的处理。
好处:封装Service层的业务逻辑有利于业务逻辑的独立性和重复利用性。

UserService

package com.example.mybits.Service;

import com.example.mybits.Dao.UserDao;
import com.example.mybits.Model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {

    @Autowired
    UserDao userDao;

    public void addUser(User user){
        userDao.addUser(user);
    }
    public void deleteUser(Integer id){
        userDao.deleteUser(id);
    }
    public void updateUser(User user){
        userDao.updateUser(user);
    }

    public List<User> selectUserAll(){
        return userDao.selectUserAll();
    }

    public List<User> selectUserById(int id){
        return userDao.selectUserById(id);
    }
    public User selectOneById(Integer id){
        return userDao.selectOneById(id);
    }

    /**通过名字查询记录**/
    public List<User> selectUserByNumber(String number){
        return userDao.selectUserByNumber(new String(number));
    }

    /**通过职称查询记录**/
    public List<User> selectUserByName(String name) {
        return userDao.selectUserByName(new String(name));
    }
}

MybitsApplication

package com.example.mybits;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;


@MapperScan("com.example.mybits.Dao")
@SpringBootApplication
public class MybitsApplication extends SpringBootServletInitializer {

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

    protected SpringApplicationBuilder config(SpringApplicationBuilder applicationBuilder){
        return applicationBuilder.sources(MybitsApplication.class);
    }
}

application.yml

application为配置文件,用 配置文件去覆盖 SpringBoot 的默认配置,可以在resources 文件夹下创建 application.yml文件,这里就以手动配置 Tomcat 端口去覆盖SpringBoot 默认配置为例,我们知道 Tomcat 默认打开端口是8080。

server:port: 8089

workname: sy
field: 111

spring:
  datasource:
    url: jdbc:mysql://localhost/demo?serverTimezone=GMT%2B8&characterEncoding=utf8&allowMultiQueries=true
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp

mybatis:
  mapper-locations: classpath:Mapper/*.xml
  type-aliases-package: com.example.mybits.Model

前端jsp页面(首页)

selectUserAll

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<head>

</head>

<body>

<div>
    <form action="selectUserById"    method="get">
        <div align='center'><input type="text" name="id"><button type="submit">按照工号搜索</button>

                <form action="selectUserByNumber"  method="get"><div align='center'><input type="text" name="number"><button type="submit">按照姓名搜索</button></div></form>
                <form action="selectUserByName"  method="get"><div align='center'><input type="text" name="name"><button type="submit">按照职称搜索</button></div></form>
            <a href="add"><button type="button">新增</button></a>
        </div>
    </form>
</div>


<table align='center' border='1' cellspacing='0'>

    <thead>
    <tr>
        <th>工号</th>
        <th>姓名</th>
        <th>职称</th>
        <th>行政区</th>
        <th>IP</th>
        <th>备注</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${user}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.number}</td>
            <td>${user.name}</td>
            <td>${user.local}</td>
            <td>${user.ip}</td>
            <td>${user.note}</td>
            <td><a href="deleteUserById?id=${user.id}"><button>删除</button></a>
            <a href="selectOneById?id=${user.id}"><button>修改</button></a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
</body></html>

增加页面

add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<head>

</head>
<body>

    <div id="section">
        <form action="addUser" method="post">
            <table class="tab" align='center' border='1' cellspacing="0" cellpadding="0" width="500" height="200">
                <tr>
                    <td>姓名:</td>
                    <td><input type="text" name="number" value="${user.number}"></td>
                </tr>
                <tr>
                    <td>职称:</td>
                    <td><input type="text" name="name" value="${user.name}"></td>
                </tr>
                <tr>
                    <td>行政区:</td>
                    <td><input type="text" name="local" value="${user.local}"></td>
                </tr>
                <tr>
                    <td>IP:</td>
                    <td><input type="text" name="ip" value="${user.ip}"></td>
                </tr>
                <tr>
                    <td>备注:</td>
                    <td><input type="text" name="note" value="${user.note}"></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="确认新增" ></td>
                    <a href="javascript:history.go(-1)"><button type="button">返回</button></a>
                </tr>
            </table>
        </form>
    </div>



</body>
</html>


查询页面

selectUserById(通过id查询)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<head>

</head>
<body>
<%--<div align='center'><a href="javascript:history.go(-1)"><button>Back</button></a></div>--%>
<table align='center' border='1' cellspacing='0'>

    <thead>
    <tr>
        <th>工号</th>
        <th>姓名</th>
        <th>职称</th>
        <th>行政区</th>
        <th>IP</th>
        <th>备注</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${user}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.number}</td>
            <td>${user.name}</td>
            <td>${user.local}</td>
            <td>${user.ip}</td>
            <td>${user.note}</td>
            <td><a href="deleteUserById?id=${user.id}"><button>删除</button></a>
                <a href="selectOneById?id=${user.id}"><button>修改</button></a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
    <a href="javascript:history.go(-1)"><button type="button">返回</button></a></td>
</table>
</body>
</html>

selectUserByName(通过name查询)

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2021/6/15
  Time: 11:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<head>

</head>
<body>
<%--<div align='center'><a href="javascript:history.go(-1)"><button>Back</button></a></div>--%>
<table align='center' border='1' cellspacing='0'>

    <thead>
    <tr>
        <th>工号</th>
        <th>姓名</th>
        <th>职称</th>
        <th>行政区</th>
        <th>IP</th>
        <th>备注</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${user}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.number}</td>
            <td>${user.name}</td>
            <td>${user.local}</td>
            <td>${user.ip}</td>
            <td>${user.note}</td>
            <td><a href="deleteUserById?id=${user.id}"><button>删除</button></a>
                <a href="selectOneById?id=${user.id}"><button>修改</button></a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
    <a href="javascript:history.go(-1)"><button type="button">返回</button></a></td>
</table>
</body>
</html>

selectUserNumber(通过Number查询)

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2021/6/15
  Time: 11:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<head>

</head>
<body>
<%--<div align='center'><a href="javascript:history.go(-1)"><button>Back</button></a></div>--%>
<table align='center' border='1' cellspacing='0'>

    <thead>
    <tr>
        <th>工号</th>
        <th>姓名</th>
        <th>职称</th>
        <th>行政区</th>
        <th>IP</th>
        <th>备注</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${user}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.number}</td>
            <td>${user.name}</td>
            <td>${user.local}</td>
            <td>${user.ip}</td>
            <td>${user.note}</td>
            <td><a href="deleteUserById?id=${user.id}"><button>删除</button></a>
                <a href="selectOneById?id=${user.id}"><button>修改</button></a>
            </td>
        </tr>
    </c:forEach>
    </tbody>
    <a href="javascript:history.go(-1)"><button type="button">返回</button></a></td>
</table>
</body>
</html>

修改页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<head>

</head>
<body>

<div id="section">
    <form action="updateUserById" method="post">
        <table class="tab" align='center' border='1' cellspacing="0" cellpadding="0" width="600" height="200">
            <tr>
                <td>工号:</td>
                <td><input type="text" name="id" value="${user.id}"></td>

            </tr>
            <tr>
                <td>姓名:</td>
                <td><input type="text" name="number" value="${user.number}"></td>
            </tr>
            <tr>
                <td>职称:</td>
                <td><input type="text" name="name" value="${user.name}"></td>
            </tr>
            <tr>
                <td>行政区:</td>
                <td><input type="text" name="local" value="${user.local}"></td>
            </tr>
            <tr>
                <td>IP:</td>
                <td><input type="text" name="ip" value="${user.ip}"></td>
            </tr>
            <tr>
                <td>备注:</td>
                <td><input type="text" name="note" value="${user.note}"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="确认修改" ></td>
                <a href="javascript:history.go(-1)"><button type="button">返回</button></a></td>
            </tr>
        </table>

    </form>


</div>



</body>
</html>

注意
1.项目命名中的mybatis书写有误,请自行修改
2.项目中表单命名,number表示名字,name表示职称,请自行修改

后期将前端页面用ajax 实现,并使用vue +element_ui实现增删改查

你可能感兴趣的:(笔记,java,spring,spring,boot,vue.js,javascript)