• 使用数据传输对象避免写多表关联查询


    @Service
    public class QuestionServiceImpl implements QuestionService {
    	@Autowired
    	private QuestionMapper questionMapper;
    	@Autowired
    	private UserMapper userMapper;
    
        @Override
        public List<QuestionDTO> findAll() {
        	List<QuestionDTO> questionDTOs = new ArrayList<>();
        	List<Question> questions = questionMapper.findAll();
        
        	User user = null;
        	QuestionDTO questionDTO = null;
        	for (Question question : questions) {
        		user = userMapper.findById(question.getPublisher());
        
        		questionDTO = new QuestionDTO();
        		BeanUtils.copyProperties(question, questionDTO);
        
        		// 为数据传输对象设置user
        		questionDTO.setUser(user);
        		questionDTOs.add(questionDTO);
        	}
        
        	return questionDTOs;
        }
    }
    

    Question.java

    @Data
    public class Question {
    	private Integer id;//
    	private String title;// varchar(50)
    	private String description;// text,
    	private Long gmtCreated;// bigint(20) DEFAULT NULL,
    	private Long gmtModified;//
    	private Integer publisher;// 问题发布者id
    	private Integer commentNum;// 评论数
    	private Integer viewNum;// 浏览数
    	private Integer likeNum;// 点赞数
    	private String tag;// 问题标签
    }
    

    传输对象

    package com.fei.dto;
    
    import com.fei.domain.User;
    
    import lombok.Data;
    
    @Data
    public class QuestionDTO {
    	private Integer id;//
    	private String title;// varchar(50)
    	private String description;// text,
    	private Long gmtCreated;// bigint(20) DEFAULT NULL,
    	private Long gmtModified;//
    	private Integer publisher;// 问题发布者id
    	private Integer commentNum;// 评论数
    	private Integer viewNum;// 浏览数
    	private Integer likeNum;// 点赞数
    	private String tag;// 问题标签
    	
    	// 数据传输对象,增加发布者User的id
    	private User user;
    }
    
  • 相关阅读:
    16-pymysql模块的使用
    15-可视化工具Navicat的使用
    14-补充内容:MySQl创建用户和授权
    13-多表查询
    12-单表查询
    11-数据的增删改
    springboot整合thumbnailator实现图片压缩
    centos7下使用yum安装redis
    springboot以jar包方式启动、关闭、重启脚本
    centos7-每天定时备份 mysql数据库
  • 原文地址:https://www.cnblogs.com/zxfei/p/11741264.html
Copyright © 2020-2023  润新知