Preface
In SpringBoot projects, code files are often placed in different packages, such as pojo, dao, service, controller, etc., but how do codes at various levels be linked and what role will they play in the project?
1. Brief description of each commonly used level
layer
The positioning of POJO in springboot project is similar to the model model layer in mvc project.
POJO (Plain Ordinary Java Object) Simple Java objects are actually ordinary JavaBeans, which contain multiple attributes and also have a get/set method. It is recommended to use @lombok annotation directly.
POJO does not write logical methods in it, and
Corresponding to the database table one by one, the attributes must also be consistent with the fields of the database table.
layer
The DAO layer is used to store the mapper interface. The mapper function is to access the database, send SQL statements to the database, complete the data addition, deletion, modification and search functions. It is usually implemented as an interface. The internal declaration method will be associated with the corresponding database function in the mapper layer.
There are two ways to write
(1) Inherit BaseMapper. The BaseMapper interface is a general mapper interface provided by MyBatis Plus. It is used to perform commonly used CRUD operations, including insertion, update, deletion and query operations. After inheriting this interface, you can automatically obtain common database operations methods without writing in the mapper
public interface UserMapper extends BaseMapper<User>{ }
(2) Call the command mvn mybatis-generator:generate through the terminal
You need to install maven and call mybatis-related dependencies. When using this command, the file will be retrieved and the DAO layer and the basic files of the pojo and mapper layer will be automatically generated according to its configuration.
Note: The requirements can be modified by changing the XML configuration, or they can be generated and then written in a new logical way.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN" "/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <classPathEntry location="E:\software\IDEA\mysql-connector-java-8.0." /> <context targetRuntime="MyBatis3"> <plugin type=""/> <commentGenerator> <property name="suppressAllComments" value="true"/> </commentGenerator> <jdbcConnection driverClass="" connectionURL="jdbc:mysql://localhost:3306/mall?characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT%2b8" userId="root" password="root"> <!--MySQL Need to specify the server time zone--> <property name="serverTimezone" value="UTC"/> <!--MySQL Not supported schema or catalog So you need to add this--> <!--refer to : /generator/usage/--> <property name="nullCatalogMeansCurrent" value="true"/> <!-- MySQL8Enabled by default SSL ,There will be a warning if not closed--> <property name="useSSL" value="false"/> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <javaModelGenerator targetPackage="" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <table tableName="Database table name" domainObjectName="The pojo class name you want to generate" enableSelectByExample="false" enableCountByExample="false" enableDeleteByExample="false" enableUpdateByExample="false"/> </context> </generatorConfiguration>
layer
Business logic layer, complete function design. Like the dao layer, you first design the interface, then create the class to be implemented, and then configure the association of its implementation in the configuration file.
The service impl is a file that integrates mapper and service. Encapsulating the service layer's business logic is conducive to the independence and reusability of the business logic.
The basic functions are:
Handling business logic: Business logic is a process of processing complex operations such as data and calculation. The Service layer is the core of business logic, which is responsible for writing and implementing business logic.
Organization DAO (Data Access Object) layer: The data access object is a code layer used to access data storage such as databases. The Service layer usually calls the DAO layer methods to process data.
Implement transaction control: Implement transaction control in the Service layer to ensure the consistency and integrity of data during the operation of the database.
Encapsulation of business objects: The Service layer will encapsulate the data required by the business logic and pass it to the DAO layer for storage or operation. This can improve the readability and maintainability of the code, as well as standardize the operation of data.
Note: @Service should be annotated on the service implementation class, otherwise it will not be scanned and recognized.
layer
Control layer, control business logic service, control requests and responses, and is responsible for front-end and back-end interactions
Controller layer mainly calls the interface in the Service layer to control specific business processes. It will not write a large amount of logical code in it. It will also accept and process some HTTP parameters, such as session
Note: @RestController should also be annotated on the CONTROLLER implementation class
layer
Store database functions and map with methods in the DAO layer. They can be generated through terminal commands or written by themselves (the workload is large). When calling DAO methods, the database method corresponding to the mapper layer will be actually executed. It is an interface bridge for database curs. At the same time, mapper scan is also needed to complete identification.
2. Other packages/levels
Enumeration package
In real project writing, you usually encounter different return values set according to different situations. Directly setting int will not only have security vulnerabilities, but also have difficulties in reading and comprehension, so enumeration can solve these problems well
@Getter public enum ProductStatusEnum { ON_SALE(1), OFF_SALE(2), DELETE(3), ; Integer code; ProductStatusEnum(Integer code) { = code; } }
Among them, the @Getter annotation is indispensable because you need to get the enum value, that is, when taking the code, you need to call the getCode() method provided by it.
Return to the object package
Since springboot projects generally adopt front-end separation, the format of data returned to the front-end by different layers and different methods is sometimes inconsistent with the properties in POJO, and may increase or may be missing. Therefore, a package used to construct the return object is directly built, and based on the requirements, it is completely consistent with the data type required by the front-end.
The structure of VO class is completely similar to that of POJO class, and it can also store a certain amount of attributes +lombok annotation (@Data)
Error packet
Since some errors in the project are not logical errors, there may be non-risk errors in normal operation of the project, and different processing needs to be done according to the type of error reported.
Through the @ExceptionHandler() annotation, change the error report class name in brackets, capture different error reports, and write corresponding error reports.
Form pack
Sometimes the parameters of the passed data object are checked in the project, and only by adding annotation to it
The annotation package is, dependencies need to be introduced
@Null The annotated element must be null
@NotNull The annotated element must not be null
@AssertTrue The annotated element must be true
@AssertFalse The annotated element must be false
@Min(value) The annotated element must be a number, and its value must be greater than or equal to the minimum value
@Max(value) The annotated element must be a number, and its value must be less than or equal to the minimum value
@Size(max,min) The size of the annotated element must be within the specified range.
@Past The annotated element must be a past time
@Future The annotated element must be a time in the future
@Pattern The annotated element must comply with the specified regular expression
5. Interceptor
The interceptor is mainly based on Java's reflection mechanism, which is an application of aspect-oriented programming (AOP), which is to call a method before the Service or a method, or call a method after the method, or even do business logic operations when an exception is thrown.
The interceptor functions similar to the Filter in a Servlet, and can be used to pre-process and post-process the processor. Using interceptors in Spring MVC and Spring Boot is generally to implement the HandlerInterceptor interface
There are three methods for this interface
(1) preHandle(): This method can implement preprocessing of the processor, that is, it will start executing before the handler method is executed. When the return value is true, it means that execution continues, and when false, subsequent interceptors or processors are not executed. Function: identity authentication, identity authorization, etc.
(2) postHandle(): This method is a post-processing callback method, that is, it is executed after the controller completes (before trying to render). Function: Pass the common model data to the view, and you can also specify the view (menu navigation, etc.) here.
(3) afterCompletion(): This method is a callback method after the request is processed, that is, it is called when the view is rendered. Function: Perform unified exception processing, log processing, etc.
After implementing the interface, rewrite the required methods and write the interceptor logic code corresponding to the project. But sometimes some links need to be open to the outside world and cannot be intercepted by interceptors, such as login interface, registration interface, etc., and another class needs to be written to implement the WebMvcConfigurer interface
@Configuration public class IntercepterConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { (new UserLoginIntercepter()) .addPathPatterns("/**") .excludePathPatterns("/error", "/user/login", "/user/register"); } }
addInterceptor: Need an interceptor instance that implements the HandlerInterceptor interface
addPathPatterns: Used to set filter path rules for interceptors; addPathPatterns("/**") intercepts all requests.
excludePathPatterns: Used to set filtering rules that do not require interception (whitelist)
Note that the @Configuration annotation cannot be omitted, otherwise the interceptor configuration may be invalid.
Here we will only explain the use of the WebMvcConfigurer interface in the interceptor. It has many other functions. If you want to know, you can check out this blog.
/weixin_45433031/article/details/121846207
3. The connection and role between levels
Three-layer architecture
Let’s start with the basic three-layer architecture. The three-layer architecture consists of the Dao layer, the Service layer, and the Controller layer. In this three-layer architecture, the Dao layer is responsible for dealing with mybatis and the database, realizing access to persistent data, isolating business logic code and data access code, and isolating the implementation of different databases.
Service is a layer responsible for writing business logic. Generally, the Service layer consists of interfaces and implementation classes, and there are a large number of business methods for call from the Controller layer. In SpringBoot projects, when writing business logic, an XXXmapper object annotated by @Autowired is often declared, which is an implementation class of the Dao layer interface for its call.
Controller, controller layer, controller layer functions for request and response control.
The Controller layer is responsible for front-end interaction, accepting front-end requests, calling the service layer, receiving data returned by the service layer, and finally returning the specific page and data to the client. Please note: the format and quantity of some return data queues are required. Pay attention to the front-end requirements and build a response Vo object to return.
Data persistence: The process of storing data into a database and reading out the data in the database is called persistence. Persistence is a mechanism to convert data in a program between instantaneous state and persistent state.
This is the end of this article about the specific implementation of various hierarchical structures in SpringBoot. For more related contents of various hierarchical structures in SpringBoot, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!