Java QueryDSL 3.6.0 Projection.bean(Person.class、Person.firstName、Person.count())
我在项目中使用QueryDSL返回按姓氏分组的人员列表和具有该姓氏的人数。下面是Person.javaJava QueryDSL 3.6.0 Projection.bean(Person.class、Person.firstName、Person.count()),java,spring-boot,orm,jpql,querydsl,Java,Spring Boot,Orm,Jpql,Querydsl,我在项目中使用QueryDSL返回按姓氏分组的人员列表和具有该姓氏的人数。下面是Person.java @Entity class Person { private String firstName; private String lastName; private boolean isCitizen; private int age; private int groupByCount; //Property to return groupByC
@Entity
class Person {
private String firstName;
private String lastName;
private boolean isCitizen;
private int age;
private int groupByCount; //Property to return groupByCount - could use Group tuple for this, but doing a research trying to set it as an object field.
//Constructors to support n! ways of object creation - where n is no of fields in the object
public Person(String lastName, int groupByCount){
this.lastName = lastName;
this.groupByCount = groupByCount;
}
public Person(int age, int groupByCount){
this.age = age;
this.groupByCount = groupByCount;
}
public Person(boolean isCitizen, int groupByCount){
this.isCitizen = isCitizen;
this.groupByCount = groupByCount;
}
// keeps going to cover all possible constructors - i want to avoid this for maintainability reasons - want to be able to build objects dynamically with different parameters
//Below is code for Getter and setters for above fields
}
下面是使用这些构造函数的QueryDSL查询
personRepo.getQueryDSL().createQuery(person).groupBy(person.lastName)
.list(Projections.constructor(Alarm.class, person.lastName, person.count());
personRepo.getQueryDSL().createQuery(person).groupBy(person.age)
.list(Projections.constructor(Alarm.class, person.age, person.count());
personRepo.getQueryDSL().createQuery(person).groupBy(person.isCitizen)
.list(Projections.constructor(Alarm.class, person.isCitizen, person.count());
如何避免写那些n!使用QueryDSL?的具有n个字段的类的构造函数??在删除Person类中的构造函数后,我尝试了如下Projections.bean
personRepo.getQueryDSL().createQuery(person).groupBy(person.isCitizen)
.list(Projections.bean(Alarm.class, person.isCitizen, person.count());
它抱怨。count()不是有效的表达式。值得注意的是,将count的值指定给person对象中的groupByCount字段。如何使用Projections.bean方法将person对象的groupByCount设置为person.count()值
提前谢谢。非常感谢您的帮助。我相信这正是您需要的。让POJO中的setter名称镜像查询中的列名-看起来您已经准备好了它。我将.as方法链接到.count到groupByCount属性之上,如下所示。这样我就可以避免写n!构造器
personRepo.getQueryDSL().createQuery(person).groupBy(person.isCitizen)
.list(Projections.bean(Alarm.class, person.isCitizen,
person.count().as(person.groupByCount));