我正在使用 Spring Boot 2.0.2.RELEASE 和 Spring Data JPA。我正在尝试在 MySql 中使用本机查询实现分页,我的代码是:
@Query(nativeQuery=true, value = "SELECT DISTINCT ud.latitude,ud.longitude,u.user_id userId FROM users u \n" +
"INNER JOIN user_devices ud ON u.id = ud.user_id\n" +
"WHERE ud.access_token IS NOT NULL AND ud.user_id <> 1\n" +
"ORDER BY calculateDistanceByLatLong(:userLat, :userLong, ud.latitude, ud.longitude) ASC \n#pageable\n",
countQuery = "SELECT COUNT(DISTINCT u.id) FROM users u \n" +
"INNER JOIN user_devices ud ON u.id = ud.user_id\n" +
"WHERE ud.access_token IS NOT NULL AND ud.user_id <> 1 \n#pageable\n")
public Page<LocationProjection> listNearByUsers(@Param("userLat")String userLatitude,@Param("userLong") String userLongitude, Pageable pageable) throws Exception;
并查看了此链接。
但它没有添加任何分页代码。当我尝试使用:
userDao.listNearByUsers(userDeviceEntity.getLatitude(),userDeviceEntity.getLongitude(), PageRequest.of(pageNo, maxResults))
例如设置 pageNo=0 和 maxResults =1,显示所有结果。所以没有实施分页。我打印了触发的查询,它是:
SELECT
DISTINCT ud.latitude,
ud.longitude,
u.user_id userId
FROM
users u
INNER JOIN
user_devices ud
ON u.id = ud.user_id
WHERE
ud.access_token IS NOT NULL
AND ud.user_id <> 1
ORDER BY
calculateDistanceByLatLong(?,
?,
ud.latitude,
ud.longitude) ASC #pageable
计数查询为:
SELECT
COUNT(DISTINCT u.id)
FROM
users u
INNER JOIN
user_devices ud
ON u.id = ud.user_id
WHERE
ud.access_token IS NOT NULL
AND ud.user_id <> 1 #pageable
我以为 Spring Data 会在主查询中添加“LIMIT 0,1”,但它不起作用。DAO接口是:
@Repository
public interface UserDao extends JpaRepository<UserEntity, Integer>{}
请提出一些解决方案。