JAVA-11-[SpringBoot] entry case of adding, deleting, modifying and checking

Spring Boot simple CRUD case
Error creating bean with name 'dataSource' defined in class path resource solution
SpringBoot startup project error Consider defining a bean of type 'xxx' in your configuration

1 The relationship between each level of Java

Domain层(POJO、Enity)
DAO层(也称为mapper层)
Service层
Controller层

1.1 Domain Layer (POJOs, Enities)

The Domain layer is usually used to place the Java Beans corresponding to the tables in the database in this system.

1. Java Bean is a code specification. When a certain class meets the following three conditions at the same time, then this class meets the Java Bean specification.

1.书写类时类中的属性全部使用private修饰
2.类中必须有一个无参构造方法。
3.为每个属性提供get/set方法。

2. POJO (Plain Ordinary Java Object): Ordinary Java objects are actually simple Java Bean entity classes, corresponding to a table in the database, and each attribute in the POJO corresponds to the fields in the table. The most obvious features of POJO are roughly as follows:

1.书写类时类中的属性全部使用private修饰;
2.类中必须有一个无参构造方法;
3.然后针对每个参数都定义了get和set方法作为访问的接口;
4.类中除了构造方法、get/set方法外不能够有其他的方法。

3. VO (value object): Value object, also known as presentation layer object, corresponds to the data object of the display interface. For example, a data list displayed on the foreground. The names and user names in this list are data that exist in two tables respectively. At this time, the query statement uses multi-table query sql when the data is displayed, and the queried data contains two tables. At this time, using a Java Bean entity class cannot store the data fields of the two tables in the returned result, so the fields or attributes used in the two tables are repackaged into a new Java Bean, and this Java Bean is called VO. In layman's terms, vo is a collection of custom attributes or fields of multiple tables.

Fourth, the Entity layer, as the name implies, is the entity layer, where entities are placed and their corresponding set and get methods. If you want to perform some operations on the database (such as reading), you must first write the entity layer.
How to write entity layer?

1.理解业务需求,分析需要从数据库中读取哪些字段;
2.根据这些字段写对应属性,写完后[自动生成get、set方法]

1.2 DAO layer (also known as mapper layer)

DAO (Data Access Object) is to write a class that encapsulates the code for accessing the database. DAO is between the database and the business logic (Service). Dao is the data access layer. The function of Dao is to encapsulate the access to the database: adding, deleting, modifying and checking does not involve business logic, but only meets the requirements of obtaining specified data according to certain conditions.

The persistence layer usually places the interface classes that execute SQL statements, deals with the database, and is responsible for executing specific business logic, such as database operations, data conversion, etc.

All operations on the database are completed in DAO, such as adding, deleting, modifying and checking the database.

1.3 Service layer

The business layer usually calls the interface of the data layer, organizes business logic functions, such as database operations, data conversion, etc., and initiates calls to the data layer according to business requirements. Usually it is also necessary to implement an interface class to facilitate calling.

The Service layer will call the DAO layer and the Domain layer, and the Service layer will also perform certain processing on the data, such as condition judgment and data screening.

Why does the service layer use interfaces to define the following advantages:
In Java, interfaces are multi-inherited, while classes are single-inherited. If you need a class to implement multiple services, you can use interfaces to define services. Not so flexible.

To provide services for different databases, we only need to implement interfaces with different classes instead of repeatedly defining classes.

1.4 Controller layer

The presentation layer usually calls the interface in the Service layer and implements the method of the interface. The controller is responsible for receiving the request and forwarding it to the corresponding view or service for processing. It is generally responsible for handling request routing and parameter validation.

The Controller layer will call the first three layers. The Controller layer generally interacts with the front-end js file for data. The Controller layer is the receiver of the front-end data, and the data processed in the background is also passed to the front-end display through the Controller layer.

2 Cases of adding, deleting, modifying and checking

2.1 Basic configuration

2.1.1 Project structure

Spring Boot.
The front end adopts html + thymeleaf template instead of jsp.

.
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com.example
│   │   │       └── crud                          --业务功能模块 即 CRUD
│   │   │           ├── controller                --Controller层
│   │   │           │    └── UserControl           
│   │   │           ├── dao                       --Dao层
│   │   │           │    └── UserDao              --Dao层接口         
│   │   │           ├── pojo                      --数据模型
│   │   │           │    └── User                 --请求体
│   │   │           ├── service                   --Service层
│   │   │           │    ├── impl                 --Service层接口的实现
│   │   │           │    │    └── UserServiceImpl 
│   │   │           │    └── UserService          --Service层接口
│   │   │           └── MyApplication.java          --启动类
│   │   └── resources
│   │       ├── static                            --静态资源
│   │       ├── templates                          --模板
│   │              ├── add.html                   --增加用户页面
│   │              ├── index.html                 --主页面
│   │              └── modify.html                --修改用户页面
└── pom.xml                                       --项目依赖

insert image description here

2.1.2 Database

一、数据库test
二、建表语句
CREATE TABLE `user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
三、插入数据
id,username,password
1,lily,1111
2,lucy,2222
3,lilei,3333

2.1.3 configuration file application.yml

spring:
  web:
    resources:
      static-locations: classpath:/static/,classpath:/templates/
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password: bigdata
    driver-class-name: com.mysql.cj.jdbc.Driver
  mvc:
    hiddenmethod:
      filter:
        enabled: true
  freemarker:
    cache: false # 页面不加载缓存,修改即使生效
mybatis:
  configuration:
    map-underscore-to-camel-case: true # 下划线驼峰设置
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl   # 打印SQL语句

2.1.4 configuration file pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/>
</parent>

<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.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

2.2 POJO

The package pojo contains the entity class User.
The entity class has three private member variables: id, username, password.
These three attributes correspond to the table user in the database test respectively.
The entity class User contains a construction method with parameters, a construction method without parameters, get and set methods corresponding to the three attributes, and also contains a rewritten toString method.

2.2.1 entity class User.java

package com.example.crud.pojo;

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

    public Integer getId() {
    
    
        return id;
    }

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

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
    //有参构造方法
    public User(Integer id,String username,String password) {
    
    
        this.id=id;
        this.username=username;
        this.password=password;
    }
    // 无参构造方法
    public User() {
    
    

    }

    @Override
    public String toString() {
    
    
        return "User{id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

2.3 Dao

The package dao contains the interface UserDao.
The annotation @Mapper is used to modify the interface UserDao.
Annotations @Insert, @Delete, @Update, @Select are used to modify the methods in the interface (addition, deletion, modification and query).

2.3.1 Interface UserDao.java

package com.example.crud.dao;
import com.example.crud.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface UserDao {
    
    
    //查询全部数据
    @Select("select * from user")
    public List<User> findAll();

    //新增数据
    @Insert("insert into user (username, password) values (#{username}, #{password})")
    public int save(User user);

    //删除数据
    @Delete("delete from user where id=#{id}")
    public int delete(int id);

    //根据ID查找用户
    @Select("select * from user where id=#{id}")
    public User get(int id);

    //根据ID更新用户数据
    @Update("update user set username=#{username},password=#{password} where id=#{id}")
    public int updateById(User user);
}

2.4 Service

The package service contains the package impl and the interface UserService of the Service layer.
Among them, the package impl contains the implementation class UserServiceImpl of the Service layer interface.
The Service layer not only needs to call the Dao layer interface, but also needs to provide the interface for the class of the Controller layer to call.

2.4.1 Interface UserService.java

package com.example.crud.service;
import com.example.crud.pojo.User;
import java.util.List;

public interface UserService {
    
    
    //查询全部数据
    public List<User> findAll();
    
    //新增数据
    public int save(User user);
    
    //删除数据
    public int delete(int id);
    
    //根据ID查找
    public User get(int id);
    
    //更新数据
    public int updateById(User user);

}

2.4.2 Interface implementation class UserServiceImpl.java

package com.example.crud.service.impl;

import com.example.crud.dao.UserDao;
import com.example.crud.pojo.User;
import com.example.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    
    
    @Autowired
    private UserDao userDao;

    @Override
    public List<User> findAll() {
    
    
        return userDao.findAll();
    }

    @Override
    public int save(User user) {
    
    
        return userDao.save(user);
    }

    @Override
    public int delete(int id) {
    
    
        return userDao.delete(id);
    }

    @Override
    public User get(int id) {
    
    
        return userDao.get(id);
    }

    @Override
    public int updateById(User user) {
    
    
        return userDao.updateById(user);
    }

}

2.5 Controller

Package controller contains class UserControl.
The annotation @Controller is used to modify the class UserControl.
The annotation @Autowired indicates that the interface provided by the Service layer is automatically injected for use by the Controller layer.

2.5.1 UserControl.java

package com.example.crud.controller;

import com.example.crud.pojo.User;
import com.example.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
public class UserControl {
    
    

    @Autowired
    private UserService userService;
    
    //查询所有用户数据
    @GetMapping("/index.html")
    public String userList(Map<String, List> result) {
    
    
        List<User> users = userService.findAll();
        result.put("users", users);
        return "index";
    }
    
    //新增数据
    @PostMapping("/add")
    public String save(User user) {
    
    
        userService.save(user);
        return "redirect:/index.html";
    }
    
    //删除数据
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable int id, HttpServletResponse servletResponse) throws IOException {
    
    
        userService.delete(id);
        System.out.println("----delete方法执行----");
        return "redirect:/index.html";
    }
    
    //根据id修改用户数据
    @GetMapping("/updatePage/{id}")
    public String updatePage(Model model, @PathVariable int id) {
    
    
        User users = userService.get(id);
        model.addAttribute("users", users);
        return "modify";
    }

    @PutMapping("/update")
    public String updateUser(Model model, User user, HttpServletRequest request) {
    
    
        String id = request.getParameter("id");
        User userById = userService.get(Integer.parseInt(id));
        userService.updateById(user);
        System.out.println(user);
        return "redirect:/index.html";
    }

}

2.6 Front-end page

There are three html files under the package templates under the package resources.
Added οnclick="return confirm('Are you sure to delete?')" to the delete button to prevent misuse.

2.6.1 Main page index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户信息主页面</title>
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<style>

    a{
    
    
        color: #ffffff;
    }
    h1{
    
    
        /*文字对齐*/
        text-align: center;
    }
    button{
    
    
        height: 50px;
        width: 50px;
        background-color: cornflowerblue;
    }
    .parent{
    
    
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .btn{
    
    
        width: auto;
    }

</style>

<body>
<h1>Spring Boot增删改查</h1>
<!--table-striped:斑马线格式,table-bordered:带边框,table-hover:鼠标悬停高亮-->
<table class="table table-striped table-bordered table-hover text-center">
    <thead>
    <tr style="text-align:center">
        <!--th标签定义html表格中的表头单元格-->
        <th style="text-align:center">编号</th>
        <th style="text-align:center">用户名</th>
        <th style="text-align:center">密码</th>
        <th style="text-align:center">操作</th>
    </tr>
    </thead>
    <!--tr标签定义html表格中的所有行-->
    <!--遍历集合,如果被遍历的变量user为null或者不存在,则不会进行遍历,也不会报错-->
    <tr th:each="user:${users}">
        <!--td标签定义html表格中的标准单元格-->
        <td th:text="${user.id}"></td>
        <td th:text="${user.username}"></td>
        <td th:text="${user.password}"></td>
        <td>
            <!--a标签用来定义超链接 href表示超链接-->
            <a class="btn btn-primary" th:href="@{'/updatePage/'+${user.id}}">更改</a>
            <a class="btn btn-danger" th:href="@{'/delete/'+${user.id}}" onclick="return confirm('确定删除?')">删除</a>
        </td>
    </tr>
</table>

<div class="parent">
    <button type="button" class="btn btn-block"><a href="/add.html">添加用户</a></button>
</div>

</body>

</html>

2.6.2 Add user page add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>添加用户页面</title>
  <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

  <body>
  <div style="width:600px;height:100%;margin-left:350px;margin-top: 180px;">
    <form action="/add" method="post">
      <!--form-control给input添加这个class后就会使用bootstrap自带的input框-->
      用户名:<input class="form-control" type="text" th:value="${username}" name="username"><br>
      <!--注意参数的拼接-->
      密 码:<input class="form-control" type="text" th:value="${password}" name="password"><br>
      <button class="btn btn-primary btn-lg btn-block">保存</button>
    </form>
  </div>
  </body>
</html>

2.6.3 Change user information interface modify.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>更改用户信息界面</title>
  <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div style="width:600px;height:100%;margin-left:350px;margin-top: 180px;">
  <form action="/update" method="post">
    <!-- rest风格中的更新是put请求,所以这块先使用post请求,然后隐藏起来改为put请求-->
    <input name="_method" type="hidden" value="put">
    ID:<input class="form-control"  type="text" th:value="${user.id}" name="id"><br>
    用户名:<input class="form-control" type="text" th:value="${user.username}" name="username"><br>
    密 码:<input class="form-control" type="text" th:value="${user.password}" name="password"><br>
    <button class="btn btn-primary btn-lg btn-block" type="submit">提交</button>
  </form>
</div>

</body>
</html>

2.7 Start class MyApplication

package com.example.crud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

2.8 Test class MyApplicationTests

package com.example.crud;

import com.example.crud.dao.UserDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class MyApplicationTests {
    
    
    @Autowired
    private UserDao userDao;
    @Test
    void contextLoads(){
    
    
        System.out.println(userDao.findAll());
    }
}

3 run

insert image description here

Guess you like

Origin blog.csdn.net/qq_20466211/article/details/129966899