当前位置:网站首页>Coding style: SSM environment in MVC mode, code hierarchical management
Coding style: SSM environment in MVC mode, code hierarchical management
2020-11-09 23:48:00 【Cicada smile】
In this paper, the source code :GitHub· Click here || GitEE· Click here
One 、 Layering strategy
MVC Pattern and code layering strategy ,MVC The full name is ModelViewController The model - View - controller , As a software design paradigm , Using a business logic 、 data 、 The interface displays the separated method organization code , Gather business logic into a component , While improving and personalizing the interface and user interaction , No need to rewrite business logic , It's a development model , But it's not the layered pattern of code in actual development , Usually SSM The framework's back-end code layers are as follows :
- controller Control layer : Define the server interface , In and out , And some input parameters ;
- service Business services layer : Assemble business logic , Business verification , The parameter model needed to build the control layer ;
- dao Data interaction layer : Provide the data query method needed by the service layer , Dealing with logic related to data interaction conditions ;
- mapper Persistence layer : be based on mybatis The framework needs native support , The most commonly used persistence layer component at present ;
Two 、 Control layer
1、Rest The interface style
Based on the logic of resource access and processing , Use different styles of annotations . For example, new resources , to update , Inquire about , Delete .
/**
* newly added
*/
@PostMapping("/insert")
public Integer insert (@RequestBody BaseInfo baseInfo){
return baseInfoService.insert(baseInfo);
}
/**
* to update
*/
@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);
}
/**
* Primary key query
*/
@GetMapping("/detail/{id}")
public InfoModel detail(@PathVariable(value = "id") Integer id) {
return baseInfoService.detail(id) ;
}
/**
* Delete primary key
*/
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable(value = "id") Integer id) {
baseInfoService.delete(id) ;
return "SUS" ;
}
2、 Interface reuse
High reuse of interfaces is not recommended , For example, add, delete, modify and check all the interfaces , The basic principle of , Different client side operations , For independent interfaces .
/**
* List loading
*/
@GetMapping("/list")
public List<BaseInfo> list() {
return baseInfoService.list(new BaseInfoExample()) ;
}
/**
* List search
*/
@PostMapping("/search")
public List<BaseInfo> search (@RequestParam("userName") String userName,
@RequestParam("phone") String phone) {
return baseInfoService.search(userName,phone) ;
}
For example, common list Interface ,list Usually, there will be conditional loading search Mechanism , And the search criteria are complex , It is suggested that there are two interfaces , From a practical point of view , Most of the scenarios are only used list Interface , Rarely used search Search for .
3、 In and out
Verification client must be conditional , For example, a certain condition is required , If there are questions , Quickly block the request link , The program entrance control layer intercepts and returns .
@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);
}
The parameters are less than three , It can be displayed directly into the reference , If there are three or more parameters, entity classes can be used to encapsulate them .
@PostMapping("/search")
public List<BaseInfo> search (@RequestParam("userName") String userName,
@RequestParam("phone") String phone) {
return baseInfoService.search(userName,phone) ;
}
4、 Processing parameters
The basic principle of the processing degree of the output parameter format , Servers as public resources , Avoid unnecessary operations , For example, the client can judge whether the return value is empty ,null etc. , Or some common format processing , Use the client to share the server pressure properly .
3、 ... and 、 Business services layer
1、 Business verification
For example, pass in the order number , Through the database layer query , No order data , This is called a business nature exception , There's no problem with the code itself , But business logic doesn't work properly .
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+" Missing data DetailInfo");
}
return buildModel(baseInfo,detailInfoEntity) ;
}
LOG.info("id="+id+" The data is completely missing ");
return null ;
}
2、 Assemble business logic
Usually, the service layer is a complex piece of logic , Used to splice business core steps , It can be determined by business logic that , Step by step, step by step , Avoid doing a lot of object creation and requirement data query at the program entrance .
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 more complex , If you want to quickly understand the business layer , Can be used for complex business methods , In this paper, we provide a method to return the parameters to build , It is used to process the parameters returned by the service layer to the control layer , This will make the heavy service layer approach clearer .
private InfoModel buildModel (BaseInfo baseInfo,DetailInfoEntity detailInfo){
InfoModel infoModel = new InfoModel() ;
infoModel.setBaseInfo(baseInfo);
infoModel.setDetailInfoEntity(detailInfo);
return infoModel ;
}
Four 、 Data interaction layer
1、 Reverse engineering
Here to use mybatis Frame or mybatis-plus Frame as a reference . If it is mybatis frame , It is suggested that the template code of reverse engineering should not be modified by user , If you need a custom method , stay mapper and xml Level to customize an extension file , Used to store custom methods and SQL Logic , This avoids the strong discomfort caused by large changes in the table structure .
Now, of course, most of them will mybatis-plus As a persistence layer component , These problems can be avoided .
2、 Data interaction
For the needs of the business layer , Provide the corresponding data query method , Only deal with the logic of interacting with the database , Avoid business logic , Especially in the distributed architecture , Data query and assembly of different services , It shouldn't be on 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) ;
}
5、 ... and 、 Source code address
GitHub· Address
https://github.com/cicadasmile/data-manage-parent
GitEE· Address
https://gitee.com/cicadasmile/data-manage-parent
版权声明
本文为[Cicada smile]所创,转载请带上原文链接,感谢
边栏推荐
- 算法模板整理(一)
- Python调用飞书发送消息
- How SSL certificate and public IP address affect SEO
- 爱康国宾怒斥国信证券报告失实,已发律师函
- 商品后台系统优化
- Leetcode 49 letter heterotopic word grouping
- CUDA_ Shared memory, memory access mechanism, access optimization
- Dongge ate grapes when he ate an algorithm problem!
- 面试官:缓存穿透、缓存雪崩和缓存击穿是什么?
- What can CRM system help enterprises do?
猜你喜欢
在PHP7下怎么大幅度提升Laravel框架性能?安装Stone!
Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
获取List集合对象中某一列属性值
Realization of commodity backstage system
How to make a set of K reverse linked lists
毕业设计之 ---基于微服务框架的电影院订票系统
11.9
嘉宾专访|2020 PostgreSQL亚洲大会阿里云数据库专场:王健
Error running app: default activity not found solution
Day84: Luffy: preferential activity strategy & User Authentication & checking / settlement of shopping cart goods
随机推荐
PL/SQL Developer临时用户和新手的功能指南
Unity使用transform.Rotate进行三维旋转角度出现偏差
11.9
Expect ':' at 0, actual = (JSON conversion exception resolution)
LeetCode 50 Pow(x,n)
The number of more than half of the array is printed by the sword
2018中国云厂商TOP5:阿里云、腾讯云、AWS、电信、联通 ...
DB engines database ranking in November: PostgreSQL holds the top spot in the same period
What can CRM system help enterprises do?
Unemployment after graduation? How do college students allocate their study time and have a complete computer knowledge system?
CUDA_ Shared memory, memory access mechanism, access optimization
Hengxun Technology: the way to deal with server downtime
November 09, 2020: talk about the similarities and differences between the bulon filter and the cuckoo filter?
Validation failed for one or more entities. See 'entityvalidationerrors' solution
算法模板整理(一)
Error running app:Default Activity not found 解决方法
【LeetCode】 92 整数反转
Hand in hand to teach you to use container service tke cluster audit troubleshooting
PLSQL Developer常用设置
Postman(一)---功能介绍