将原始SQL查询映射到DTO对象Spring中

问题描述 投票:0回答:1

SPRING BOOT,JAVA 11和POSTGRES

我有一个很大的SQL查询:

select c.*, cat.id,cat.name
from client_organization o join organization c
on o.organization_id = c.id
join client w on o.client_id = w.id
join org_category cat on c.category_id = cat.id
where w.id = ?

所以我需要将给定的结果转换为数据传输对象列表(DTO)。如果重要的话,这里是我的DTO(不包括构造函数,getter和setter):

public class OrganizationListDto {
    Long id;
    String image;
    Boolean status;
    String name;
    Long categoryId;
    String categoryName;
}

我一直在寻找解决方案,发现该操作可以通过不同的方式(jdbc,休眠等)实现。因此,请向我解释什么以及何时需要使用它们?如何执行此操作?

java sql postgresql hibernate jdbc
1个回答
0
投票
Follow the below approach have used spingJpa

@服务公共类OrganizationServiceImpl

{
    @Autowired
    OrganizationListRepository organizationListRepository;

        public OrganizationListDto  fetch(usrId)
        {
        OrganizationListDto orgListData = new OrganizationListDto();
    List<OrganizationListMapping> orgData = organizationListRepository.fetchData(usrId);
    BeanUtils.copy(orgData,orgListData)

        return orgData;
        }

}

@存储库公共接口OrganizationListRepository扩展了JpaRepository {

@Query(native="true",value="select  cat.id as id,cat.name as name
from client_organization o join organization c
on o.organization_id = c.id
join client w on o.client_id = w.id
join org_category cat on c.category_id = cat.id
where w.id = usrId"
OrganizationListMapping fetchData(@Param ("usrId") Integer usrId);
}

public interface OrganizationListMapping {
    public Long getId();
    public String getName();

}


public class OrganizationListDto {
    Long id;
    String name;

}
© www.soinside.com 2019 - 2024. All rights reserved.