我将 Spring Boot 1.5 和 spring data JPA 与 MySQL 结合使用。我尝试在单个表上运行简单的计数查询,但找不到比这更好的方法来映射查询结果:
存储库:
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();
}
Service:
@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());
}
I use 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,但是您需要将类路径硬编码到查询中才能使其正常工作,而且我仍然需要将对象映射到不可变对象。
使用 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;
}
}
spring data JPA 有类似的东西吗@Query
?