您无法在默认实现中传递 GroupBy 子句。要得到你想要的输出,首先你必须实现自定义存储库,其次你必须编写自己的方法和逻辑。
第一步:
写一个新的仓库接口:
import org.springframework.data.repository.NoRepositoryBean;
import com.querydsl.core.types.Predicate;
import java.util.Map;
@NoRepositoryBean
public interface EnterpriseRepositoryCustom {
Map<Integer, Long> countByMonth(Predicate predicate);
}
现在将此接口继承到您现有的EnterpriseRepository:
public interface EnterpriseRepository extends
PagingAndSortingRepository<Enterprise, String>,
QuerydslPredicateExecutor<Enterprise>,
EnterpriseRepositoryCustom{}
然后新建自定义仓库的实现类:
import com.querydsl.core.group.GroupBy;
import com.querydsl.core.types.Predicate;
import org.springframework.data.jpa.repository.support.QueryDslRepositorySupport;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public class EnterpriseRepositoryImpl extends QueryDslRepositorySupport
implements EnterpriseRepositoryCustom {
public EnterpriseRepositoryImpl() {
super(Enterprise.class);
}
@Override
public Map<Integer, Long> countByMonth(Predicate predicate) {
//Have to write logic here....
}
}
第二步:
在countByMonth方法中写下你的逻辑如下:
public Map<Integer, Long> countByMonth(Predicate predicate) {
Map<Integer, Long> countByMonth = getQuerydsl()
.createQuery()
.from(QEnterprise.enterprise)
.where(predicate)
.transform(GroupBy
.groupBy(QEnterprise.enterprise.dateCreated.month())
.as(QEnterprise.enterprise.count()));
return countByMonth;
}
可选:
如果您想按月获取记录列表,则只需修改 count as -
Map<Integer, List<Enterprise>> recordByMonth = getQuerydsl()
.createQuery()
.from(QEnterprise.enterprise)
.where(predicate)
.transform(GroupBy
.groupBy(QEnterprise.enterprise.dateCreated.month())
.as(GroupBy.list(QEnterprise.enterprise)));
希望你找到答案了!!
示例github project。