Spring数据JPA @Query映射与命名列

时间:2018-03-01 10:41:35

标签: java spring spring-boot spring-data-jpa jdbctemplate

我使用Spring Boot 1.5和Spring数据JPA与MySQL。我试图在一个表上运行一个简单的计数查询,但找不到比这更好的映射查询结果的方法。:

存储库:

@Override
public List<SourceModuleStatDTO> getSourceModuleStats() {
    List<Object[]> objects = vehicleRepository.sourceModuleStats();

    return objects.stream()
            .map(o->SourceModuleStatDTO.from((String)o[0], (Long)o[1]))
            .collect(Collectors.toList());
}

服务:

@Value.Immutable
@JsonSerialize(as = ImmutableSourceModuleStatDTO.class)
@JsonDeserialize(as = ImmutableSourceModuleStatDTO.class)
public abstract class SourceModuleStatDTO {
    public abstract String sourceModule();
    public abstract long vehicleCount();

    public static SourceModuleStatDTO from(String sm, long c) {
        return ImmutableSourceModuleStatDTO.builder()
                .sourceModule(sm)
                .vehicleCount(c)
                .build();
    }
}

我使用org.immutables,所以DTO。:

JdbcTemplate

这里的问题是映射,我需要转换结果或手动检查所有内容。即使RowMapper具有更好的映射功能,我也无法相信没有更好的方法可以做到这一点。

我也尝试了这个:https://stackoverflow.com/a/36329166/840315,但你需要将类路径硬编码到Query中以使其工作,我仍然需要将对象映射到Immutables。

使用JdbcTemplate,您可以使用private static final class EmployeeMapper implements RowMapper<Employee> { @Override public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee(); employee.setCountry(rs.getString("country")); employee.setEmployeeName(rs.getString("employee")); return employee; } } src):

@Query

春季数据JPA {{1}}是否有类似内容?

1 个答案:

答案 0 :(得分:4)

如何使用Projections如下?

static interface VehicleStats { 
    public String getSourceModule();
    public Long getVehicleCount();
}

您的存储库方法将是

@Query("select v.sourceModule as sourceModule, count(v) as vehicleCount from Vehicle v group by v.sourceModule")
List<VehicleStats> sourceModuleStats();

在Service类中,您可以使用以下界面方法。

List<VehicleStats> objects = vehicleRepository.sourceModuleStats();
return objects.stream()
        .map(o->SourceModuleStatDTO.from(getSourceModule(),getVehicleCount() )
        .collect(Collectors.toList());
相关问题