Spring Concept用于将数据注入Spring托管模型映射器方法并保存DB调用

时间:2020-09-20 06:21:51

标签: spring spring-boot spring-mvc spring-data-jpa spring-data

问题陈述-在当前的实现中,我正在使用ModelMapper将实体列表转换为DTO列表。 DTO有一个额外的布尔字段,需要根据数据库值导出。因此,在将实体列表转换为DTO列表的同时,我为每个记录创建了数据库命中。我正在寻找一种解决方案来优化这一点。有没有办法,我可以在一次调用中从数据库获取所有必需的值,然后将其注入到modelmapper方法中。下面是我的代码

服务等级

@Service
@Slf4j
@Transactional
public class LeadActivityService
{
    @Autowired
    LeadActivityRepo laRepo;
    
    public Boolean getRevertable(Long leadActivityId, Long leadId) throws Exception
    {
        List<LeadActivity> activities = laRepo.fetchMostRecentLeadActivity(leadId);
        if (activities.size() < 1)
            throw new Exception("No activities found for lead");
        LeadActivity activity = activities.get(0);
        if (leadActivityId.equals(activity.getLeadActivityId()))
        {
            // some business logic
            return true;
        }
        return false;
    }
}

模型映射器类

@Mapper(componentModel="spring")
public abstract class LeadActivityMapper 
{
    @Autowired
    LeadActivityService leadActivityService;
    
    public abstract LeadActivityOnLeadInformationDTO mapLeadActivityToDTO(LeadActivity leadActivity) throws Exception;
    public abstract List<LeadActivityOnLeadInformationDTO> mapLeadActivitiesToDTOs(List<LeadActivity> leadActivity) throws Exception;
    
    @BeforeMapping
    public void setRevertable(LeadActivity la, @MappingTarget LeadActivityOnLeadInformationDTO laDto) throws Exception 
    {
        laDto.setIsRevertable(leadActivityService.getRevertable(la.getLeadActivityId(),la.getLead().getLeadId()));
    }
    
}

我正在使用此映射器的服务方法

@Autowired
    LeadActivityMapper laMapper;

public AllActivitesForLeadDAO getAllActivitiesForLead(Long leadId) throws Exception
    {
        log.info("Invoked getAllActivitiesForLead");
        Lead lead = getLeadFromLeadId(leadId);
        AllActivitesForLeadDAO allActivitesForLeadDAO = new AllActivitesForLeadDAO();
        allActivitesForLeadDAO.setPendingActivities(
                laMapper.mapLeadActivitiesToDTOs(laRepo.fetchPendingActivitiesForLead(lead.getLeadId())));
        allActivitesForLeadDAO.setPastActivities(
                laMapper.mapLeadActivitiesToDTOs(laRepo.fetchPastActivitiesForLead(lead.getLeadId())));
        return (allActivitesForLeadDAO);
    }


0 个答案:

没有答案