带有命名列的弹簧数据JPA @Query映射



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

存储库:

public interface VehicleRepository extends JpaRepository<Vehicle, String> {
    @Query("select v.sourceModule as sourceModule, count(v) as vehicleCount from Vehicle v group by v.sourceModule")
    List<Object[]> sourceModuleStats();
}

服务:

@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());
}

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

@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();
    }
}

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

我也尝试过:https://stackoverflow.com/a/36329166/840315,但是您需要将Code classPath用在查询中才能使其工作,而且我仍然需要将对象映射到Immutables。/p>

使用jdbctemplate,您可以使用RowMapper(SRC(:

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;
    }
}

弹簧数据JPA @Query

是否有类似的东西

如何使用下面的投影?

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();

在您的服务类中,您可以使用下面的接口方法。

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

最新更新