Share an example of SpringBoot with front and rear end separation, which is suitable for beginners to learn

1. Package structure of SpringBoot

2. Relationship between packages

Controller: it is mainly responsible for the process control of specific business modules and will call the interface of Service layer to control business logic
DAO: no matter what the framework is, we often interact with the database. If we all have to write SQL statements in a scenario, our code will be very redundant. Therefore, we thought of encapsulating the database to make our database look like dealing with an object, which is usually DAO. When we operate this object, the object will automatically generate SQL statements to interact with the database. We only need to use DAO. Usually, we write interfaces in the DAO layer, which has methods to deal with data.
DaoImpl: the specific implementation of the interface in Dao package, including some database operation statements.
Entity: entity class, in which the entity class information corresponds to the data in the database
mapper: entity class mapping. The interface of RowMapper is used to map the column fields in the database to the attributes in Java beans, so that we can perform assignment operations. We also want to use beans in JDBC setName(rs.getString(“Name”)); Spring abstracts this code into an interface, that is, the RowMapper we want to implement here.
Service: service is a relatively independent functional module, which is mainly responsible for business logic application design. First, you should also design the interface, and then design the class that implements the interface. In this way, we can call the service interface for business processing in the application. The service layer business implementation specifically calls the defined DAO interface and encapsulates the service layer business logic, which is conducive to the independence and reusability of the general business logic.
ServiceImpl: implement the Service interface and call the methods of Dao layer.

3. Code sharing

NO.1--------Controller.java

package com.example.controller;

import com.example.entity.Student;
import com.example.service.studentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;


/**
 * Call the service layer, and the main function is in the Application layer
 */

@Controller  // Necessary annotations in the Controller layer
@AllArgsConstructor    // The function on the studentService and Student classes is to construct their constructor and instantiate these two variables
public class studentController {

    private final studentService studentservice;
    private final Student student;

    /**
     * Find all
     */
    @RequestMapping("listAll")
    public void listAll() {
        // Find list data
        List<Student> students = studentservice.SelectAll();
        // Lists the found information
        System.out.println(students);
    }

    @RequestMapping("listBySex")
    public List<Student> listBySex(boolean sex) {
        List<Student> students1 = studentservice.SelectBySex(sex);
        if (students1.toString().equals("Fei Zhang")) {
            return null;
        }
        return students1;
    }

}

NO.2--------xxxdao.java

package com.example.dao;

import com.example.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

/**
 * @program: Spring-Prepare
 * @author: Lu Tao
 * @create: 2021-12-20
 **/

/**
 * Persistence layer, interface layer, interaction with the database, programming methods for database operation.
 * @Mapper No
 */
public interface studentDao {

    List<Student> SelectAll();

    List<Student> SelectBySex(Boolean sex);

    String Insert();

}

NO.3--------xxxDaoImpl.java

package com.example.dao.Impl;

import com.example.dao.studentDao;
import com.example.entity.Student;
import com.example.mapper.StudentMapper;
import lombok.AllArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.util.List;
@AllArgsConstructor    // Construction method of automatically building JDBC template
@Repository
/**
 * @Repository Can only be labeled in DAO class:
 * This is because the annotation not only identifies the class as a Bean, but also encapsulates the data access exception thrown in the marked class as the data access exception type of Spring.
 * Spring It provides a rich data access exception structure independent of the specific data access technology, which is used to encapsulate the exceptions thrown by different persistence layer frameworks, so that the exceptions are independent of the underlying framework.
 **/
@Service  // Automatically inject into the Spring container without redefining the bean
public class studentImpl implements studentDao {

    // Get object
    private JdbcTemplate jdbcTemplate;

    // Query all student information
    @Override
    public List<Student> SelectAll() {
        String sql = "select * from student";
        return jdbcTemplate.query(sql, new StudentMapper());
    }

    // Query all information of students of the same gender
    @Override
    public List<Student> SelectBySex(Boolean sex) {
        String sql = "select * from student where sex <> true";
        return jdbcTemplate.query(sql, new StudentMapper());
    }

    // Add student information
    @Override
    public String Insert() {
    return null;
    }
}

NO.4--------xxxEntity.java

package com.example.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.Date;
@Data   
@AllArgsConstructor 
@NoArgsConstructor  
/**
 * Entity class information
 */
@Repository(value = "/Student")
public class Student {
    // Set the student name database to varchar type
    private String name;
    // Set the student age database to type int
    private int age;
    // The database of student gender 0 (male) and 1 (female) is set to tinyint type
    private boolean sex;
    // The student ID number database is set to int, but the length is not enough.
    private Integer IDCord;
    // Set the student birthday database to Date type
    private Date birthDay;
}

NO.5--------xxxMapper.java

package com.example.mapper;

import com.example.entity.Student;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
/**
 * Entity class mapping
 * RowMapper The interface of is used to correspond the column fields in the data to the attributes in the java Bean, so that you can assign values.
 * Also like beans in JDBC setName(rs.getString(“name”); Spring abstracts this code and writes it as RowMapper
 */

public class StudentMapper implements RowMapper<Student> {
    @Override
    public Student mapRow(ResultSet resultSet, int i) throws SQLException {
    
        Student student = new Student();
        
        student.setName(resultSet.getString("name"));
        student.setAge(resultSet.getInt("age"));
        student.setSex(resultSet.getBoolean("sex"));
        student.setIDCord(resultSet.getInt("IDCord"));
        student.setBirthDay(resultSet.getDate("BirthDay"));
        
        return student;
        
    }
}

NO.6--------xxxService.java

package com.example.service;

import com.example.entity.Student;
import java.util.List;

/**
 * Service layer, call to dao layer
 */
public interface studentService {

    List<Student> SelectAll();

    List<Student> SelectBySex(Boolean sex);

    String Insert();
}

NO.7--------xxxServiceImpl.java

package com.example.service.serviceImpl;

import com.example.dao.studentDao;
import com.example.entity.Student;
import com.example.service.studentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * The implementation of the methods in the interface service also completes the function of calling the methods in the Dao layer
 * Add @ Service to the front as the mapping
 */
@Service  // With this annotation, this class will be automatically injected into the spring container, and it does not need to be in ApplicationContext The bean is defined again in the XML file
@Repository  // Acts on the studentDao class defined to
@AllArgsConstructor  // When injecting dao layer methods, create a construction method and initialize the variable "studentdao"
@Transactional  // AOP interception and transaction processing are required, which will affect the performance. It will only work for public. On the implementation class that implements the interface
public class studentServiceImpl implements studentService {

    /*Method of injecting dao layer*/
    private final studentDao studentdao;

    @Override
    public List<Student> SelectAll() {
        return studentdao.SelectAll();
    }

    @Override
    public List<Student> SelectBySex(Boolean sex) {
        return studentdao.SelectBySex(sex);
    }

    @Override
    public String Insert() {
        return studentdao.Insert();
    }
}

NO.8--------application.yml

spring:
  # Annotation linked database
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/*****?useUnicode=true&characterEncoding=UTF-8
    username: ******
    password: *******
    dbcp2:
      max-idle: 20
      min-idle: 10

# Annotations make tomcat port numbers not conflicting
server:
  port: 8888

NO.9 -------- here is a Test for your reference, studentcontrollertest java

package com.example.test.controller;
import com.example.SpringbootApplication;
import com.example.entity.Student;
import com.example.service.studentService;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

@RunWith(SpringRunner.class)
// Is a runner, which needs to be specified when running. Spring runner is spring JUnit 4classrunner Class, its role is the same as that of spring junit4classrunner Class is the same
@SpringBootTest(classes = {SpringbootApplication.class})
// Specify the startup class, or do not write the information in parentheses
public class studentControllerTest {

    @Autowired
    // Inject the interface that studentService has been implemented, but if the interface is modified by final, it needs to be initialized.
    private studentService studentservice;

    @Test
    public void SeeAll() {
        try {
            List<Student> students = studentservice.SelectAll();
            System.out.println(students);
        } catch (Exception e) {
            System.out.println("Finding all failed,Failure reason: " + e);
        } finally {
            System.out.println("*************Find all, code execution completed***********\n");
        }
    }

    @Test
    public void SeeBySex() {
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            boolean sex = bufferedReader.markSupported();
            List<Student> selectBySex = studentservice.SelectBySex(sex);
            System.out.println(selectBySex);
        } catch (Exception e) {
            System.out.println("When searching all by gender, the result is wrong. The reason for failure is:  " + e);
        } finally {
            System.out.println("*************Find all by gender, and the code is executed***********\n");
        }
    }
}

4. Welcome advice

If you have any questions or need advice, please leave a message or contact me directly qq: 2748508180. Thanks***

Keywords: Java Spring Spring Boot

Added by aisalen on Wed, 29 Dec 2021 12:26:29 +0200