2

Here is my query

select SUM(d.day) as totalDay, SUM(d.month) as totalMonth from record d where d.userId = ?1
Integer getRecod(Long id);

As the query is not returning integer, error occurs. What should i replace with integer?

mahfuj asif
  • 1,691
  • 1
  • 11
  • 32
  • There is not standard way of doing so, check this https://stackoverflow.com/questions/4371384/can-a-jpa-query-return-results-as-a-java-map – Aman Oct 28 '20 at 14:49

2 Answers2

5

Solution 1: Create a model with totalDay and totalMonth and create an all args constructor.

public class UserDataModel {
    Long totalDay;
    Long totalMonth;

    public UserDataModel(Long totalDay, Long totalMonth) {
        this.totalDay = totalDay;
        this.totalMonth = totalMonth;
    }
    
    //getter and setter
}

Change your query like

@Query(value = "select 
new com.package.UserDataModel(SUM(d.day) as totalDay, SUM(d.month) as totalMonth) 
from Record d where d.userId = ?1 ")
    UserDataModel getRecord(Long id);

Solution 2: using spring projection. Create an interface like this. Make sure to follow proper camcelCase.

public interface UserDataModelV2 {
    Long getTotalDay();
    Long getTotalMonth();
}

Change your moethod like this.

    @Query(value = "select " +
            " SUM(d.day) as totalDay, SUM(d.month) as totalMonth " +
            "from Record d where d.userId = ?1")
    List<UserDataModelV2> getRecord(Long id);

If you want to return a HashMap instead of a POJO, you can extend UserDataModel with hashMap and put data in the map in the constructor.

public class UserDataModel extends HashMap<String, Object>{
    Long totalDay;
    Long totalMonth;

    public UserDataModel(Long totalDay, Long totalMonth) {
        this.totalDay = totalDay;
        this.totalMonth = totalMonth;
        put("totalDay",totalDay); 
        put("totalMonth",totalMonth); 
    }
    
    //getter and setter
}

Or you can replace the Interface in Solution 2 with a Map<Stirng, Object>.

@Query(value = "select " +
            " SUM(d.day) as totalDay, SUM(d.month) as totalMonth " +
            "from Record d where d.userId = ?1")
    List<Map<Stirng, Object>> getRecord(Long id);
Shawrup
  • 2,478
  • 2
  • 12
  • 21
1

you should replace Integer with Object[] :

Object[] getRecod(Long id);

because SUM(d.day) as totalDay, SUM(d.month) as totalMonth return two long value in array