我试图在扩展CrudRepository的存储库中执行一些SQL查询。我在控制器中有以下代码:
@CrossOrigin(origins = "*") @GetMapping(path="/all") public @ResponseBody List<UserProjection> getAllRequestResponseRecords() { return userRequestResponseRepository.findAllProjectedBy() ; }
DAO代码如下:
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(); }
该类是:
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; } }
投影为:
public interface UserProjection { String getU_httpstatus(); String getU_queryparam(); }
我对如何添加查询(诸如此类)感到困惑:
select u_type,count(u_type) from u_user_click_data group by u_type
我如何更改投影,还有哪些其他必要的更改?
您可以将DAO更改为下面,这应该可以工作。
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();
}
确保Bean类构造函数应具有传递的参数。
验证查询是否为有效的JPA查询(此处)。