想象一下这个参议员,我有一个班级:
public class TOTO{
private int Id;
private Boolean bool1;
private Boolean bool2;
private Boolean name;
//constructor
//getters
//setters
}
我也有一个spring数据存储库:
public interface TOTORepository extends JpaRepository<TOTO, Long> {
@Query( "SELECT COUNT(*),toto from TOTO toto where toto.bool1=false groub by name " )
List<TOTO> getIncidentDepart();
}
我想得到的结果是:按名称分组的对象数量。另一个问题,我可以在反对级别存储COUNT(*)变量。
答案 0 :(得分:0)
您需要创建一个单独的bean类(TOTOGroupingByNameData
),这需要从@Query
填充以获得如下结果:
TOTOGroupingByNameData Bean类:
public class TOTOGroupingByNameData {
private String name;
private Long count;
public TOTOGroupingByNameData(String name, Long count) {
this.name = name;
this.count = count;
}
}
存储库界面:
public interface TOTORepository extends JpaRepository<TOTO, Long> {
@Query(value = "select new TOTOGroupingByNameData(t.name, count(t)) from TOTO t where where t.bool1=false group by t.name")
List<TOTOGroupingByNameData> findCountByName();
}
P.S:假设该名称为String
类型,如果您的问题中的boolean
更改为boolean
类型。
答案 1 :(得分:0)
您可以在TOTO类中使用自定义构造函数,并添加Transient字段来存储计数结果。
例如,你的TOTO课程将是:
public class TOTO{
private int Id;
private Boolean bool1;
private Boolean bool2;
private Boolean name;
@Transient
private Long totalNumber;
// constructor you will use in your query
public TOTO(int Id, Boolean bool1, Boolean bool2, Boolean name, Long totalNumber){
this.Id = Id;
this.bool1 = bool1;
this.bool2 = bool2;
this.name = name;
this.totalNumber = totalNumber;
}
//getters
//setters
}
查询就像:
@Query( "SELECT new package.to.Toto(toto.id, toto.bool1, toto.bool2, toto.name, count(*) as totalNumber) from TOTO toto where toto.bool1=false groub by toto.name " )
List<TOTO> getIncidentDepart();
使用这种方法时,请记住在实例化构造函数时将包写入TODO类。