JPA联表查询或返回其他参数结果接收处理
1、使用一个自定义VO类去接收:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FormContainItemCountVO {
private Long formId;
private String formName;
private Long itemCount;
}
JPA Repository方法:
@Query(value = "select new com.chakid.dto.statics.FormContainItemCountVO (f.id,f.fromName,count(i.id)) from Form f left join FormWithItem i on f.id = i.formId group by f.fromName")
List<FormContainItemCountVO > countItemCountGroupByFormName();
2、使用一个自定义接口接收:
前缀加get以驼峰方式命名,sql那需要用别名指定,才能正确映射到!!
public interface StaticsPublishFormV2VO {
String getFormIds();
/**
* 对应时间单位
*/
String getCheckTimeUnit();
/**
* 对应时间单位包含的数量
*/
Long getCount();
}
JPA Repository方法:
@Query(value = "SELECT GROUP_CONCAT(form_id) as formIds,CONCAT( YEAR(create_time),'-',MONTH(create_time)) as checkTimeUnit,COUNT(*) as count FROM tbl_publish_form WHERE check_time = ?1 and create_time BETWEEN ?2 and ?3 GROUP BY CONCAT( YEAR(create_time),'-',MONTH(create_time))", nativeQuery = true)
List<StaticsPublishFormV2VO> staticsPublishFormMonth(String checkTime, Date startTime, Date endTime);
想要获取返回的结果,直接调用对应的get方法即可。
这两种方法的是区别是,第一个不是采用的原生SQL,有些SQL函数不支持,第二种使用的是原始SQL,支持的函数更多。