zoukankan      html  css  js  c++  java
  • 使用数据传输对象避免写多表关联查询

    @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;
    }
    
  • 相关阅读:
    [Luogu] 借教室
    [Luogu] 子共七
    [Luogu] 让我们异或吧
    【bzoj1030】[JSOI2007]文本生成器
    HDU3068 最长回文
    【bzoj2342】[Shoi2011]双倍回文
    【NOIP2012】借教室
    HDU2203 亲和串
    【POJ2001】Shortest Prefixes
    vodevs3031 最富有的人
  • 原文地址:https://www.cnblogs.com/zxfei/p/11741264.html
Copyright © 2011-2022 走看看