Reputation: 483
I'm trying to execute some SQL queries in my repository which extends CrudRepository. I have the following code in Controller:
@CrossOrigin(origins = "*")
@GetMapping(path="/all")
public @ResponseBody List<UserProjection> getAllRequestResponseRecords() {
return userRequestResponseRepository.findAllProjectedBy() ;
}
The DAO code is as following:
public interface UserRequestResponseRepository extends CrudRepository<UserRequestResponse, Integer> {
//public static final String FIND_QUERY = "select user.u_httpstatus ,user.u_queryparam from UserRequestResponse user";
public static final String FIND_QUERY =
"select new com.abc.datacollection.entity.UserRequestResponse(user.u_httpstatus ,user.u_queryparam) from UserRequestResponse user";
@Query(value = FIND_QUERY)
//public List<UserProjection> getAllRequestResponseRecords();
List<UserProjection> findAllProjectedBy();
}
The class is:
import java.sql.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity // This tells Hibernate to make a table out of this class
public class UserRequestResponse {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String u_httpstatus;
private String u_error_message;
private String u_queryparam;
public UserRequestResponse(String u_httpstatus, String u_queryparam) {
this.u_httpstatus = u_httpstatus;
this.u_queryparam = u_queryparam;
}
public String getU_httpstatus() {
return u_httpstatus;
}
public void setU_httpstatus(String u_httpstatus) {
this.u_httpstatus = u_httpstatus;
}
public String getU_error_message() {
return u_error_message;
}
public void setU_error_message(String u_error_message) {
this.u_error_message = u_error_message;
}
public String getU_queryparam() {
return u_queryparam;
}
public void setU_queryparam(String u_queryparam) {
this.u_queryparam = u_queryparam;
}
}
The projection is:
public interface UserProjection {
String getU_httpstatus();
String getU_queryparam();
}
I am confused about how I can add queries like (something like this):
select u_type,count(u_type) from u_user_click_data group by u_type
How do I change the projection and what are the other necessary changes?
Upvotes: 1
Views: 1775
Reputation: 2670
You can change the DAO to below and this should work.
public interface UserRequestResponseRepository extends CrudRepository<UserRequestResponse, Integer> {
public static final String FIND_QUERY =
"select new com.abc.datacollection.entity.UserRequestResponse(user.u_httpstatus ,user.u_queryparam, COUNT(user.u_type)) from UserRequestResponse user GROUP BY user.u_type";
@Query(value = FIND_QUERY)
//public List<UserProjection> getAllRequestResponseRecords();
List<UserProjection> findAllProjectedBy();
}
Make sure the Bean class constructor should have the passing parameters.
Verify that the query is valid JPA query(here).
Upvotes: 1