Coding style: SSM environment in Mvc mode, code layered management

Source code of this article: GitHub·click here || GitEE·click here

1. Stratification strategy

MVC pattern and code layering strategy. The full name of MVC is ModelViewController, which is model-view-controller. As a model of software design, it organizes code in a way of separating business logic, data, and interface display, and gathers business logic into one In the component, while improving and customizing the interface and user interaction, there is no need to rewrite the business logic. This is a development mode, but it is not a layered mode of the code in actual development. Usually the back-end code of the SSM framework is divided into The layers are as follows:

Coding style: SSM environment in Mvc mode, code layered management

  • Controller control layer: define server interface, input and output parameters, and check some input parameters;
  • service business service layer: assembling business logic, business verification, and constructing the parameter model required by the control layer;
  • dao data interaction layer: provide data query methods required by the service layer, and process logic related to data interaction conditions;
  • Mapper persistence layer: based on the native support required by the mybatis framework, a very commonly used persistence layer component;

Second, the control layer

1. Rest interface style

Based on the logic of resource access and processing, different styles of annotations are used. For example, resource addition, update, query, delete.

/**
 * 新增
 */
@PostMapping("/insert")
public Integer insert (@RequestBody BaseInfo baseInfo){
    return baseInfoService.insert(baseInfo);
}
/**
 * 更新
 */
@PutMapping("/update/{id}")
public String update(@PathVariable(value = "id") Integer id,
                     @RequestBody BaseInfo baseInfo) {
    if (id<1){
        return "error";
    }
    baseInfo.setId(id);
    return "update="+baseInfoService.update(baseInfo);
}
/**
 * 主键查询
 */
@GetMapping("/detail/{id}")
public InfoModel detail(@PathVariable(value = "id") Integer id) {
    return baseInfoService.detail(id) ;
}
/**
 * 主键删除
 */
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable(value = "id") Integer id) {
    baseInfoService.delete(id) ;
    return "SUS" ;
}

2. Interface reuse

It is not recommended that the interface be highly reused. For example, adding, deleting, modifying, and checking each interface is sufficient. The basic principle is that different client operations are independent of the interface.

/**
 * 列表加载
 */
@GetMapping("/list")
public List<BaseInfo> list() {
    return baseInfoService.list(new BaseInfoExample()) ;
}
/**
 * 列表搜索
 */
@PostMapping("/search")
public List<BaseInfo> search (@RequestParam("userName") String userName,
                              @RequestParam("phone") String phone) {
    return baseInfoService.search(userName,phone) ;
}

For example, the common list interface, list usually has a search mechanism that is loaded according to conditions, and the judgment conditions for search are very complicated. It is recommended to divide into two interfaces. From practical considerations, most scenarios only use the list interface, and rarely Use search to search.

3. Entry and exit

Verify the necessary conditions of the client, such as certain conditions must be filled in, etc. If there is a problem, quickly block the request link, so that the program entry control layer intercepts the return.

@PutMapping("/update/{id}")
public String update(@PathVariable(value = "id") Integer id,
                     @RequestBody BaseInfo baseInfo) {
    if (id<1){
        return "error";
    }
    baseInfo.setId(id);
    return "update="+baseInfoService.update(baseInfo);
}

If the parameters are less than three, you can directly display them. If the parameters are three or more, you can use the entity class to encapsulate.

@PostMapping("/search")
public List<BaseInfo> search (@RequestParam("userName") String userName,
                              @RequestParam("phone") String phone) {
    return baseInfoService.search(userName,phone) ;
}

4. Parameter processing

The basic principle of parameter format processing is that the server is a public resource to avoid unnecessary operations. For example, the client can determine whether the return value is empty, null, etc., or handle some common formats, and use the client to appropriately share the server pressure.

Three, business service layer

1. Business verification

For example, the incoming order number is queried by the database layer, and there is no order data. This is called an exception of business nature. There is no problem with the code itself, but the business logic cannot be executed normally.

public InfoModel detail(Integer id){
    BaseInfo baseInfo = baseInfoDao.selectByPrimaryKey(id) ;
    if (baseInfo != null){
        DetailInfoEntity detailInfoEntity = detailInfoDao.getById(id);
        if (detailInfoEntity == null){
            LOG.info("id="+id+"数据缺失 DetailInfo");
        }
        return buildModel(baseInfo,detailInfoEntity) ;
    }
    LOG.info("id="+id+"数据完全缺失");
    return null ;
}

2. Assemble business logic

Normally, the service layer is a complex piece of logic, used to splice the core steps of the business, and the program can be executed step by step through business logic judgments, avoiding a large number of possible object creation and demand data queries at the program entry.

public int insert (BaseInfo record){
    record.setCreateTime(new Date());
    int insertFlag = baseInfoDao.insert(record);
    if (insertFlag > 0){
        DetailInfoEntity detailInfoEntity = new DetailInfoEntity();
        detailInfoEntity.setUserId(record.getId());
        detailInfoEntity.setCreateTime(record.getCreateTime());
        if(detailInfoDao.save(detailInfoEntity)){
            return insertFlag ;
        }
    }
    return insertFlag;
}

3. Data model construction

Usually the business layer is a bit complicated. If you want to quickly understand the business layer, you can provide a method of returning to the complex business method to process the parameters that the service layer needs to return to the control layer, so that The heavy service layer method becomes clearer.

private InfoModel buildModel (BaseInfo baseInfo,DetailInfoEntity detailInfo){
    InfoModel infoModel = new InfoModel() ;
    infoModel.setBaseInfo(baseInfo);
    infoModel.setDetailInfoEntity(detailInfo);
    return infoModel ;
}

Fourth, the data interaction layer

1. Reverse engineering

Here to use mybatis framework or mybatis-plus framework as a reference. If it is the mybatis framework, it is recommended that the template code of the reverse engineering is not customized. If you need to customize the method, customize an extension file at the mapper and xml level to store the customized method and SQL logic, so as to avoid tables Strong discomfort caused by major structural changes.

Coding style: SSM environment in Mvc mode, code layered management

Of course, most of them now use mybatis-plus as a persistence layer component, which can avoid the above problems.

2. Data interaction

In response to the needs of the business layer, provide corresponding data query methods, only process the logic of interaction with the database, and avoid business logic, especially in the distributed architecture, data query and assembly of different services should not appear in this layer.

public interface BaseInfoDao {

    int insert(BaseInfo record);

    List<BaseInfo> selectByExample(BaseInfoExample example);

    int updateByPrimaryKey(BaseInfo record);

    BaseInfo selectByPrimaryKey(Integer id);

    int deleteByPrimaryKey(Integer id);

    BaseInfo getById (Integer id) ;
}

Five, source code address

GitHub·地址
https://github.com/cicadasmile/data-manage-parent
GitEE·地址
https://gitee.com/cicadasmile/data-manage-parent

Recommended reading: finishing programming system

Serial number project name GitHub address GitEE address Recommended
01 Java describes design patterns, algorithms, and data structures GitHub·click here GitEE·Click here ☆☆☆☆☆
02 Java foundation, concurrency, object-oriented, web development GitHub·click here GitEE·Click here ☆☆☆☆
03 Detailed explanation of SpringCloud microservice basic component case GitHub·click here GitEE·Click here ☆☆☆
04 Comprehensive case of SpringCloud microservice architecture actual combat GitHub·click here GitEE·Click here ☆☆☆☆☆
05 Getting started with SpringBoot framework basic application to advanced GitHub·click here GitEE·Click here ☆☆☆☆
06 SpringBoot framework integrates and develops common middleware GitHub·click here GitEE·Click here ☆☆☆☆☆
07 Basic case of data management, distribution, architecture design GitHub·click here GitEE·Click here ☆☆☆☆☆
08 Big data series, storage, components, computing and other frameworks GitHub·click here GitEE·Click here ☆☆☆☆☆

Guess you like

Origin blog.51cto.com/14439672/2548589
Recommended