java - 使用 Spring Projection Interface 的 native 查询来选择字段

标签 java spring spring-boot spring-data

我想知道如何填充这些类:

interface BaseDTO {

    Integer getId();

    String getNome();

    Boolean getAtivo();

    RegionalDTO getRegional();

    MunicipioDTO getMunicipio();
}

interface RegionalDTO {

    Integer getId();
}

interface MunicipioDTO {

    Integer getId();
}

并运行此查询

@Query(value = "SELECT " +
        "base.ID_BASE AS id, base.NOME AS nome, base.ATIVO AS ativo, " +
        "regional.ID_REGIONAL AS ID_REGIONAL, " +
        "municipio.ID_MUNICIPIO AS ID_MUNICIPIO " +
        "FROM TB_BASE base " +
        "LEFT JOIN TB_REGIONAL regional on base.ID_REGIONAL = regional.ID_REGIONAL " +
        "LEFT JOIN TB_MUNICIPIO municipio on base.ID_MUNICIPIO = municipio.ID_MUNICIPIO " +
        "ORDER BY base.ID_BASE", nativeQuery = true)
List<BaseDTO> getAll();

所以我想选择查询中的字段,因为稍后我会将更多字段放入这些 DTO 中。

最佳答案

我认为最简单的方法是使用仅包含 regionalmunicipio id 的简单接口(interface)。调用 getAll 后,将此接口(interface)映射到适当的类结构(其中 ids 转换为 dtos)。

List<RealDTO> result = repository.getAll().stream()
  .map(i -> new RealDTO(i))
  .collect(Collectors.toList());

关于java - 使用 Spring Projection Interface 的 native 查询来选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59941491/

相关文章:

java - System.gc() 收集仍然被局部变量引用的对象

java - LongAdder 为何比 AtomicLong 表现更好

java - 无法在 Spring Boot 中为每个测试方法初始化数据库

java - 重复API调用的持久连接

java - 如何修复 javax.persistence.Table.indexes()[Ljavax/persistence/Index?

java - 尝试在 Spring Boot/Spring Security Web 应用程序中打开 .css 文件时,为什么会收到 "405 - Method Not Allowed"错误?

eclipse - 无法发布 web 应用程序 : SpringSource Tool Suite problem?

java - 是否可以将表名作为 liquibase 变更集中的参数传递?

spring - 无法在 Debug模式下启动 SpringBoot 应用程序,正在关闭 org.springframework.context.annotation.AnnotationConfigApplicationContext

serialization - Spring-data-redis @Cacheable java.lang.ClassCastException : java. util.HashMap 无法转换为 java.lang.String