/** * 房间已经预定的时间统计表 */public interface RoomOrderTimeRepository extends JpaRepository{ @Query("select new com.ddzrh.dto.RoomOrderTimeOutPut(r.orderTime,COUNT(r.orderTime) )" + " from RoomOrderTime as r " + " where r.roomTypeId =:roomId"+ " GROUP BY r.orderTime" ) List queryRoomOrderTime(@Param("roomId") Integer roomId); }
@Datapublic class RoomOrderTimeOutPut { private Date orderTime; private Long orderNum; public RoomOrderTimeOutPut(Date orderTime, Long orderNum) { this.orderTime = orderTime; this.orderNum = orderNum; } }
使用@Query(value = "select new com.wd.cloud.uoserver.dto.TjVO(u.orgId ,count(u.orgId)) from User u group by orgId")进行查询。
@Valuepublic class TjVO { Long orgId; Long registerCount;}/** * 按机构统计注册人数 * @param pageable * @return */ @Query(value = "select new com.wd.cloud.uoserver.dto.TjVO(u.orgId ,count(u.orgId)) from User u group by orgId") Page tjByOrgId(Pageable pageable);
/** * 按天统计注册人数 * @return */ @Query(value = "select DATE_FORMAT(gmt_create,\"%Y-%m-%d\") as registerDate,count(*) as registerCount from user group by registerDate",nativeQuery = true) List tj(); /** * 按机构统计注册人数 * @param pageable 分页 * @return */ @Query(value = "select org_id as orgId,count(*) as registerCount from user group by orgId", countQuery = "select count(*) from user group by org_id", nativeQuery = true) Page tjByOrgId(Pageable pageable);
测试:
@RunWith(SpringRunner.class)@SpringBootTestpublic class UoServerApplicationTests { @Autowired UserRepository userRepository; @Test public void contextLoads() { List tjDTOList = userRepository.tj(); tjDTOList.forEach(tjDTO -> { Console.log("registerDate={},registerCount={}", tjDTO.getRegisterDate(), tjDTO.getRegisterCount()); }); }}
结果日志:
Hibernate: select DATE_FORMAT(gmt_create,"%Y-%m-%d") as registerDate,count(*) >as registerCount from user group by registerDate registerDate=2019-01-28,registerCount=7393 registerDate=2019-03-07,registerCount=1
需求:根据机构分组,统计机构总人数和用户类型为2的人数
@Componentpublic class SpecBuilder { @PersistenceContext private EntityManager entityManager; public List
测试:
@RunWith(SpringRunner.class)@SpringBootTestpublic class UoServerApplicationTests { @Autowired SpecBuilder specBuilder; @Test public void contextLoads() { List tjDTOList1 = specBuilder.tj(169L); tjDTOList1.forEach(tjDTO -> { Console.log("orgId={},总人数={},管理员人数={}", tjDTO[0], tjDTO[1], tjDTO[2]); }); }}