Back end learning log:

Posted by ma5ect on Mon, 04 Oct 2021 05:49:35 +0200

Took a relatively complete springboot MVC framework and source code for corresponding learning

Interpretation of SpringBootMVC structure:

For SpringBoot, a framework with high cohesion and low coupling must comply with a logical difficulty that can withstand a large number of development. Some developers develop alone. The main development problem they face is how to remember every function they have written, and some functions and functions may overlap, It may be necessary to call many of the same functions or basically similar writing methods or functions. How to organize the coupling and cohesion between these functions to achieve a more harmonious balance, which requires a set of MVC mechanism to manage code calls. In front of ordinary developers, this mechanism may be used to manage code and be interpreted at a deeper level.

View layer: the code used to accept requests submitted by users, that is, the Controller layer used in our developed projects. This layer is responsible for integrating the services used by front-end developers and exposing the interface. It is used to accept requests and incoming parameters from front-end developers and extract and integrate them, Then, the front-end request is logically called to the interface of the service layer.

Service layer: the business logic of the system is mainly completed here. The user request is processed in the View layer, and the function of the Service layer is invoked to realize the specific operation and to invoke the operation of the back-end database, so as to realize the whole logic layer.

Dao layer: the database will be operated during the logical implementation of the Service layer. Dao layer is a series of functions and classes that operate on the database.

These three layers will expose their provided functions in the form of interfaces or abstractions. The calls from the upper layer to the lower layer are realized through interfaces, and the lower layer is the real provider of the logic or required services of the upper layer.

In addition to these three layers, for the database operation, that is, the Dao layer, we can also abstract the relationship returned from the database into an entity class. Therefore, the parameters passed out during the database operation in the Dao layer will be automatically encapsulated into their previously defined entity class, that is, entity, directly by the annotation and encapsulated interface in SpringBoot, If we use the traditional mybatis to generate the structure, there will be a more traditional XML injection, so there will be a mapping relationship between the corresponding Dao layer and XML. For this relationship, each Dao operation class will find the id corresponding to its own interface name in Mapper.xml. After specifying the incoming and outgoing parameters, Reasonable mapping can be carried out. Whenever a service of the service layer calls the interface called by the Dao layer to the database, the Dao interface will automatically map the XML tag of the interface called in its corresponding Mapper.xml under the encapsulation of annotations. After finding the tag, the structured sql language written in the tag will be injected into the database, So as to realize the operation of the corresponding database.

Interpretation of SpringBoot annotation:

For general use, if mybatis is not used, I use it as follows:

First, we start with the entity layer, which generally does not need annotation, because it is only an entity class.

When the corresponding entity class is written, we begin to operate on the DAO database layer. In Dao, Mapper first needs to map this interface to the corresponding XML, and then, according to my habit, directly inject database operations into the corresponding interface, directly above the interface with @ Insert or @ Delete, for example:

public interface PaperMaitainDao{
  @Insert("INSERT INTO paper_maitain (tea_id,paper_id,qulid_id) VALUES (#{teaId}, #{paperId},#{qualifId})")
	boolen insertPaperMaitain(PaperMaitain paperMaitian);
  //PaperMaitain is an entity class in entity
}

After completing the logic composition of this layer, we start the Service layer to a higher level. Here, we need to register a Service interface @ Service

Then inject the interface service corresponding to the Dao to be used, usually @ Resource or @ Autowired

Then we can write the corresponding service interface

@Service
public class TeacherService{
  @Resource
  private PaperMaintainDao paperMaintainDao;
  
  public Boolean createPaperMaintain(PaperMaintain paperMaintain){
        try {
           return paperMaintainDao.insertPaperMaintain(paperMaintain);
        } catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}

After our service is written, the next step is to connect a series of service operations with the front end to the Controller layer

First, declare that the corresponding Controller uses @ RestController

Then we need to make correspondence on the route. The general interface @ RequestMapping(value = "/ teacher") will be opened on the root/teacher

@RestController
@RequestMapping(value = "/teacher")
public class TeacherController {
    @Resource
    private TeacherService teacherService;
  //Here is to directly call the service layer and introduce resources
  
  //To make a route mapping under / teacher, you need root/teacher/createPaperMaintain to access this interface
  	@RequestMapping(value = "/createPaperMaintain")
    @ResponseBody
    public Result createPaperMaintains(@RequestBody Map<String, Object> request){
        int teaId = (int) request.get("tea_id");
        String paperId = (String) request.get("paper_id");
        Integer qualifId = (Integer) request.get("qualif_id");
        PaperMaintain paperMaintain  = new PaperMaintain();
        paperMaintain.setPaperId(paperId);
        paperMaintain.setQualifId(qualifId);
        paperMaintain.setTeaId(teaId);
        return Result.succ(teacherService.createPaperMaintain(paperMaintain));
    }
}

About dealing with the array passed in from the front end

The array passed in from the front end is actually a separate ArrayList for java, so it can be accepted separately. Therefore, the following operations will be performed

1. If the front end directly transmits an array, it will directly (@ requestbody ArrayList < type of json in the array corresponding to the entity class > request) at the interface level of the Controller
2. Directly define the corresponding received entity class in the entity class, and then define the type of data to be delivered by the front end

For example, the following entity class:

public class StudentCourseUpdaterCollection {
    private Integer courseId;
    private List<StudentCourseUpdater> studentCourseUpdaters;

    public Integer getCourseId() {
        return courseId;
    }

    public void setCourseId(Integer courseId) {
        this.courseId = courseId;
    }

    public List<StudentCourseUpdater> getStudentCourseUpdaters() {
        return studentCourseUpdaters;
    }

    public void setStudentCourseUpdaters(List<StudentCourseUpdater> studentCourseUpdaters) {
        this.studentCourseUpdaters = studentCourseUpdaters;
    }
}

Then the receiving interface of the back end is as follows:

@RequestMapping(value = "/updateStuCourseByKey")
    @ResponseBody
    public Result updateStuCourseByKey(@RequestBody StudentCourseUpdaterCollection studentCourseUpdaterCollection){

        ArrayList<Integer> ids= new ArrayList<Integer>();

        //System.out.println(studentCourseUpdaterCollection.getCourseId());
        for( StudentCourseUpdater studentCourseUpdater: studentCourseUpdaterCollection.getStudentCourseUpdaters() ){
            try {
                if(teacherService.updateStuCourseByKey(studentCourseUpdater)==0){
                    ids.add(studentCourseUpdater.getStuId());
                }

            }catch (Exception  e) {
                    ids.add(studentCourseUpdater.getStuId());
                    //System.out.println(studentCourseUpdater.getStuId());
            }
            //System.out.println(studentCourseUpdater.getScore());
        }
        if(ids.size()==0){
            return Result.succ("Operation succeeded");
        }else {
            String msg="";
            for (int id:ids){
                msg+=id+",";
            }
            return Result.fail("Operation failed!"+"fail id: "+msg);
        }

    }

The front end should also follow the corresponding format when passing parameters

{
    "courseId":480120,
    "studentCourseUpdaters":[
        {
            "stuId":201656788,
            "courseId":80120,
            "score":79
        }
    ]
}

The above is a rough analysis of a springboot from the whole to the part. It is also the operation of participating in the practice of the knowledge learned earlier this week.

Topics: Java Back-end mvc