Reputation: 453
I want to map results to data transfer objects but I don't know what is the proper way for this issue.
Since there are lots of result rows I don't think it's a nice solution if I parse the return objects for each of them and assign them to currently created data transfer object.
public class MaintenanceTaskRepositoryImpl implements CustomMaintenanceTaskRepository {
@Autowired
EntityManager em;
@Override
public List<Object []> findRepairCostForLast5Year() {
List<Object []> results = em.createNativeQuery(
"SELECT YEAR(END_DATE) AS YEAR," +
" SUM(PRICE) AS REPAIR_COST" +
" FROM MAINTENANCE_TASK" +
" WHERE TYPE_OF_WORK = 'PREVENTIVE' AND" +
" DATEDIFF(YEAR, END_DATE , CURRENT_DATE) < 6" +
" GROUP BY YEAR(END_DATE) " +
" LIMIT 5").getResultList();
return results;
}}
Above query returns multiple rows that's why it's a list of object array. It works right now but I want my method directly returns list of DTO.
My DTO class is below.
public class RepairCostDto {
private int year;
private BigDecimal cost;
public RepairCostDto(int year, BigDecimal cost) {
this.year = year;
this.cost = cost;
}
public RepairCostDto() {
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public BigDecimal getCost() {
return cost;
}
public void setCost(BigDecimal cost) {
this.cost = cost;
}}
Thank you in advance.
Edit:
above return is like,
[[year,cost],[year1,cost1],[year2,cost2]]
but I want it as below,
[RepairCostObj,RepairCostObj1, RepairCostObj2...]
Edit2:
Referring this and this answers should I apply the solution that I mentioned above?
Upvotes: 2
Views: 2225
Reputation: 326
this should be what you want
@PersistenceContext
private EntityManager entityManager;
@Transactional
public List<RepairCostDto> listRepairCost(){
String sql = "xxxxxxxx";
SQLQuery sqlQuery = entityManager.createNativeQuery(sql).unwrap(SQLQuery.class);
Query query = sqlQuery.setResultTransformer(Transformers.aliasToBean(RepairCostDto.class));
List<RepairCostDto> list = query.list();
entityManager.clear();
return list;
}
Also, I think specification would be a better way to do it.
Upvotes: 1