java - 将原始 sql 查询映射到 DTO 对象 Spring

标签 java sql postgresql hibernate jdbc

Spring Boot、JAVA 11、POSTGRES

我有一个很大的 SQL 查询:

select c.id,c.image_url,c.status,c.name, 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,hibernate等) 那么请解释一下我需要什么以及何时需要使用它们? 如何实现这个操作?

最佳答案

Follow the below approach have used spingJpa

@服务 公共(public)类OrganizationServiceImpl

{
    @Autowired
    OrganizationListRepository organizationListRepository;

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

        return orgData;
        }

}

@存储库 公共(public)接口(interface) 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;

}

关于java - 将原始 sql 查询映射到 DTO 对象 Spring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60431797/

相关文章:

postgresql - Postgres 全局关闭自动提交

重载方法的 Java 动态转换

Java继承和方法重载

java - 在同一个表中使用两个结果集时发生错误

postgresql - 在 Windows 中使用 .bat 备份 Postgresql

database - 获取创建的表名

java - 无法从 Windows 生成在 WSL 2 上运行的 Kafka 主题

mysql - 这个查询MYSQL怎么写

sql - RPC和普通链接服务器选择的性能差异

sql - Postgresql 从要比较的日期中提取 monthYear