为了账号安全,请及时绑定邮箱和手机立即绑定

SpringMVC-DTO应用介绍

标签:
SSM Spring

DTO

Data transfer object (DTO) is an object that carries data between processes. The motivation for its use has to do with the fact that communication between processes is usually done resorting to remote interfaces (e.g. web services), where each call is an expensive operation.Because the majority of the cost of each call is related to the round-trip time between the client and the server, one way of reducing the number of calls is to use an object (the DTO) that aggregates the data that would have been transferred by the several calls, but that is served by one call only.
The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behavior except for storage and retrieval of its own data (accessors and mutators). DTOs are simple objects that should not contain any business logic that would require testing

前言

图片描述
实践见真知,我通过自己写小的 Demo 小的项目慢慢发现一些很实用的知识点。之前在学习并使用 SSM 框架时,由于需要快速开发,所以我对我不熟悉的知识点就直接抛弃,比如 DTO 层,我觉得没有什么用处,后端 API 构建的时候就直接返回 entity 对象的 JSON 串,当时使用的时候并没有觉得有什么不妥,但是由于上一篇返回自定义信息的文章,我进行了总结,我发现返回信息也是需要进行封装的,比如加入状态码、提示信息,还有返回多个对象。

需求

根据最近一直沿用的项目,电影点播系统,当返回电影信息的时候,因为电影的语言只有一种,所以语言和电影的关系是一对一的,使用 SQL 结合 resultMap 就能实现,但是,一个电影的分类可以有很多种,例如《白日梦想家》可以是喜剧、剧情、家庭等,那么就出现一对多的情况,也就是 SQL 的返回值是多行的,于是我想到解决办法就是封装一个返回结果,当查询到电影的基本信息后,用电影的 ID 再去查询一次数据库,统一封装到 DTO 层然后返回。

代码

public class MovieExecution {
	//结果状态
	private int stateCode;
	//状态标识
	private String stateInfo;
	//返回结果
	private List<Movie> movieList;
	//关联种类
	private List<Type> typeList;
	
	public MovieExecution(){		
	}
	//失败
	public MovieExecution(MovieStateEnum movieStateEnum){
		this.stateCode=movieStateEnum.getState();
		this.stateInfo=movieStateEnum.getStateInfo();
	}
	//成功
	public MovieExecution(MovieStateEnum movieStateEnum,List<Movie> movieListItem){
		this.stateCode=movieStateEnum.getState();
		this.stateInfo=movieStateEnum.getStateInfo();
		this.movieList=movieListItem;
	}
	/* getter setter */
}

Controller

@RequestMapping(value = "/getbyid/{id}", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getbyid( HttpServletRequest request,@PathVariable(value="id")int idnum,HttpServletResponse response){
		Map<String, Object> modelMap = new HashMap<String, Object>();
		MovieExecution movieExe=movieService.getMovieById(idnum);
		if(movieExe==null){
			//如果没查询到结果
			response.setStatus(404);
		}
		modelMap.put("movie", movieExe);
		return modelMap;
	}

效果图

图片描述
图片描述

点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
29
获赞与收藏
154

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消