提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、DTO & DO
- 二、示例
- 1. 定义Controller
- 2.定义Service和实现
- 3.定义Mapper
- 4.前端访问测试
- 总结
前言
提示:这里可以添加本文要记录的大概内容:
这里记录下使用SpringBoot结合Mybatis-plus快速构建CRUD接口通用示例。
mybatis-plus是mybatis的超集,可以放心使用,具体参考官网。
提示:以下是本篇文章正文内容,下面案例可供参考
一、DTO & DO
以下是一些概念的厘清,理解因人而异。
DO、PO、VO、DTO等其实都是一个JavaBean,只是应用的范围不同,表示的意义不同,而这些不同是Java这么多年来形成的一种约定,这种习惯形成Java程序员之间一种共识。有些人喜欢把返回给前端的对象封装为VO、有些人喜欢将和数据交互的对象定义为DAO ,也有人喜欢返回前端使用DTO代替,总之屏蔽了MySQL原始的数据库表的细节,只需要对外暴露不同即可。我们为了方便,统一定义DTO为和前端进行数据交互的组件,DO就是和数据库表具有严格映射关系的对象了。每个人风格不同,但是大体表达的意思是一样的。
二、示例
SpringBoot单体应用大都包含Controller/Service/Mapper 这三个重要模块,其他诸如实体类Entity、DTO,甚至request/response
可以依据自己是否需要来定义,不过最好遵循公司内部的规范来,否则维护起来真的挺麻烦。
1. 定义Controller
以下是CRUD代码(示例):
@Api("Topic管理")
@Slf4j
@RestController
@RequestMapping("/topic")
public class TopicController {
@Autowired
private TopicService topicService;
@PostMapping("/addOrUpdateTopic")
@ApiOperation("添加或更新Topic")
public Result<String> addOrUpdateTopic(@RequestBody @NotNull AddTopicRequest addTopicRequest) {
try {
topicService.saveOrUpdate(addTopicRequest);
} catch (Exception e) {
log.error("{} # applyTopic Error: {}", this.getClass().getName(), e.getMessage());
return Result.errorData("Topic添加或更新失败", e.getMessage());
}
return Result.successMessage("Topic添加或更新成功!");
}
@PostMapping("/queryTopics")
@ApiOperation("查询topics: 依据Topic名称,owner搜索")
public Result<IPage<TopicDTO>> queryTopics(@RequestBody TopicQueryRequest queryDTO) {
IPage<TopicDTO> topicDTOList = null;
try {
topicDTOList = topicService.queryAllTopics(queryDTO);
} catch (Exception e) {
log.error("{} # queryTopics Error: {}", this.getClass().getName(), e.getMessage());
return Result.errorData(topicDTOList);
}
return Result.successData(topicDTOList);
}
@GetMapping("/findOne/{name}")
@ApiOperation("根据topic name 查询topic")
public Result<TopicDO> findOneTopic(@PathVariable("name") @NotNull String name) {
return Result.successData(topicService.queryOneTopic(name));
}
@DeleteMapping("/deleteTopic/{id}")
@ApiOperation("删除Topic")
public Result<String> deleteTopic(@PathVariable @NotNull Long id) {
try {
topicService.deleteTopic(id);
} catch (Exception e) {
log.error("{} # deleteTopic Error: {}", this.getClass().getName(), e.getMessage());
return Result.errorData("Topic删除失败", e.getMessage());
}
return Result.successMessage("Topic删除成功!");
}
2.定义Service和实现
代码如下(示例):
定义接口:
public interface TopicService {
void saveOrUpdate(AddTopicRequest addTopicRequest);
void deleteTopic(Long id);
TopicDO queryOneTopic(String topicName);
IPage<TopicDTO> queryAllTopics(TopicQueryRequest queryDTO);
}
接口实现:
@Service("TopicService")
public class TopicServiceImpl extends ServiceImpl<TopicMapper, TopicDO> implements TopicService {
@Autowired
private TopicMapper topicMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public void saveOrUpdate(AddTopicRequest request) {
TopicDO topicDO = TopicDO.builder()
.id(request.getId())
.topicName(request.getTopicName())
.owner(request.getOwner())
.description(request.getDescription())
.partitionNum(request.getPartitionNum() == 0 ? TopicConstant.DEFAULT_PARTITION_NUM : request.getPartitionNum())
.replicaNum(request.getReplicaNum() == 0 ? TopicConstant.DEFAULT_REPLICA_NUM : request.getReplicaNum())
.retentionTime(request.getRetentionTime() == 0 ? TopicConstant.DEFAULT_RETENTION_TIME : request.getRetentionTime())
.build();
if (0 == topicDO.getId() || null == topicDO.getId()) {
this.save(topicDO);
} else {
this.updateById(topicDO);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void deleteTopic(Long id) {
this.removeById(id);
}
@Override
public TopicDO queryOneTopic(String topicName) {
return this.getOne(Wrappers.<TopicDO>lambdaQuery().eq(TopicDO::getTopicName, topicName));
}
@Override
public IPage<TopicDTO> queryAllTopics(TopicQueryRequest queryDTO) {
if (queryDTO.getPageNo() == 0 || null == queryDTO.getPageNo()) {
queryDTO.setPageNo(1);
}
if (queryDTO.getPageSize() == 0 || null == queryDTO.getPageNo()) {
queryDTO.setPageSize(10);
}
Page<TopicDTO> page = new Page<>(queryDTO.getPageNo(), queryDTO.getPageSize());
if (StringUtils.isNotBlank(queryDTO.getKeyword())) {
queryDTO.setKeyword("%" + queryDTO.getKeyword() + "%");
}
IPage<TopicDTO> topicLists = topicMapper.queryPage(page, queryDTO);
return topicLists;
}
}
3.定义Mapper
mapper用于和数据库打交道,类似于DAO,以下是一个mapper接口,申明了之后就具备一些操作的特性。
原因是因为拿到的 mapper 其实是一个代理对象,底层调用的是 SqlSession 的方法,SqlSession 的方法里其实调用的 Executor 的方法。
其实就是配置文件+动态代理的增强。
@Repository
public interface TopicMapper extends BaseMapper<TopicDO> {
IPage<TopicDTO> queryPage(Page<TopicDTO> page, @Param("queryDTO") TopicQueryRequest queryDTO);
}
其实我们继承Mapper接口后,可以不用在写配置文件就可以进行crud功能,但是如果需要自定义的内容还是需要。
>
public interface BaseMapper<T> extends Mapper<T> {
TopicMapper.xml (可有可无,但是为了通用也便于后期维护扩展建议一定要有)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xx.dao.TopicMapper">
<resultMap id="topicResultMap" type="com.xx.topic.TopicDTO">
<result column="id" property="id"/>
<result column="topic_name" property="topicName"/>
<result column="partition_num" property="partitionNum"/>
<result column="replica_num" property="replicaNum"/>
<result column="retention_time" property="retentionTime"/>
<result column="owner" property="owner"/>
<result column="description" property="description"/>
<result column="create_time" property="createTime"/>
<result column="update_time" property="updateTime"/>
</resultMap>
<select id="queryPage" resultMap="topicResultMap">
SELECT
id,topic_name,partition_num,replica_num,retention_time,owner,description,create_time,update_time
FROM topic where is_deleted = 0
<if test="queryDTO.keyword != null and queryDTO.keyword.trim() != '' ">
AND ( topic_name LIKE #{queryDTO.keyword} OR `owner` LIKE #{queryDTO.keyword} )
</if>
</select>
</mapper>
4.前端访问测试
http://localhost:8080/swagger-ui.html#/topic-controller
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210401152540368.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTA4MzQwNzE=,size_16,color_FFFFFF,t_70)
总结
构建一个SpringBoot的单体应用目前来看越来越容易,到处可以使用的轮子,甚至很多开源的Demo都可以用来借鉴,比如有了mybatis-plus 对mybatis的增强,Lombok简化代码书写等,但是希望越来越快捷的同时可能也要多一点的思考,不然难以精进。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)