0

I have one Object say Student with following parameter :

Student{
String name;
int marks;
String department;
Subject subject;

//getters and setters

}

I want to get the count(student), department from student group by department using crudRepository.

What will be the return type of the method that we will define in the crudrepository? How should I write the whole flow? I am getting exception.

Below is the code snippet of repository :

@Query("select new com.myProject.MyObject(mec.serviceName, count(mec)) " +
            "from migration_entity_count mec where mec.workflowRequestId = :workflowRequestId " +
            "group by mec.serviceName order by mec.serviceName")
    List<EntitiesByServiceName> getMigrationEntitiesCountByServiceName(@Param("workflowRequestId") Long workflowRequestId);
}

MyObject has 2 paramters : Long and String

Satam Guin
  • 25
  • 5
  • Please show what you tried so far as well the whole error message with stacktrace. – Rashin Jun 21 '19 at 12:47
  • Put the sample code and exception trace. I would recommend to go through with Spring-Data-JPA working example first . Then if not solvable, post the exception – sitakant Jun 21 '19 at 12:58
  • I have uploaded the changes ... I want to know if this will work and what will be the return type of this function getMigrationEntitiesCountByServiceName(Long id); This above function is written in an interface extending Crudrepository Interface of different object – Satam Guin Jun 24 '19 at 06:59
  • since you select `select new com.myProject.MyObject` it must be `List`. Look here: https://stackoverflow.com/questions/36328063/how-to-return-a-custom-object-from-a-spring-data-jpa-group-by-query – Dmitrii Bocharov Jun 24 '19 at 11:15
  • I am having this exception while running the mvn clean-install : Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method getMigrationEntitiesCountByServiceName(Long) and I have imported MyObject class in the java file – Satam Guin Jun 27 '19 at 19:01

1 Answers1

0

Below query will give you, your expected result and in Java the return type will be ResultSet. You can covert it to your own object type.

SELECT department, COUNT(*) 
FROM Student
GROUP BY department;
Pradyskumar
  • 296
  • 1
  • 3
  • 15
  • But I want to return it from a CrudRepository Interface ... for that what will be the return type in java while storing the data into a list ... – Satam Guin Jun 24 '19 at 06:38
  • It will be a List of Custom objects. For example the Custom object class is like CustomObject{ String department; long count; } then return type will be List – Pradyskumar Jun 25 '19 at 07:14
  • I am having this exception while running the mvn clean-install : Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method getMigrationEntitiesCountByServiceName(Long) – Satam Guin Jun 27 '19 at 18:59