我正在尝试将Spring-Data-JPA整合到我的项目中。让我困惑的一件事是如何通过注释实现setMaxResults(n)?
例如,我的代码:
public interface UserRepository extends CrudRepository<User , Long>
{
@Query(value="From User u where u.otherObj = ?1 ")
public User findByOtherObj(OtherObj otherObj);
}
我只需要从otherObj返回one (and only one)
用户,但是我找不到注释maxResults的方法。有人能给我个提示吗?
(mysql抱怨:
com.mysql.jdbc.JDBC4PreparedStatement@5add5415: select user0_.id as id100_, user0_.created as created100_ from User user0_ where user0_.id=2 limit ** NOT SPECIFIED **
WARN util.JDBCExceptionReporter - SQL Error: 0, SQLState: 07001
ERROR util.JDBCExceptionReporter - No value specified for parameter 2
)
我找到了一个链接:https://jira.springsource.org/browse/DATAJPA-147,我试过了,但失败了。现在看起来不可能了吧?为什么Spring-Data中没有内置如此重要的特性?
如果我手动实现此功能:
public class UserRepositoryImpl implements UserRepository
我不得不在CrudRepository
中实现大量的预定义方法,这太可怕了。
环境: spring-3.1、spring-data-jpa-1.0.3.RELEASE.jar、spring-data-commons-core-1.1.0.RELEASE.jar
发布于 2012-02-17 01:26:35
从Spring Data JPA 1.7.0 (Evans发布系列)开始。
您可以使用新引入的Top
和First
关键字来定义查询方法,如下所示:
findTop10ByLastnameOrderByFirstnameAsc(String lastname);
Spring Data将自动将结果限制为您定义的数量(如果省略,则默认为1)。请注意,结果的排序在这里变得相关(通过示例中看到的OrderBy
子句,或者通过将Sort
参数传递给方法)。在有关new features of the Spring Data Evans release train的博客文章或documentation中可以了解更多信息。
对于以前的版本
为了只检索数据片段,Spring data使用了分页抽象,该抽象在请求端使用Pageable
接口,在结果端使用Page
抽象。所以你可以从
public interface UserRepository extends Repository<User, Long> {
List<User> findByUsername(String username, Pageable pageable);
}
并像这样使用它:
Pageable topTen = new PageRequest(0, 10);
List<User> result = repository.findByUsername("Matthews", topTen);
如果您需要知道结果的上下文(它实际上是哪个页面?是第一个吗?总共有多少个?),使用Page
作为返回类型:
public interface UserRepository extends Repository<User, Long> {
Page<User> findByUsername(String username, Pageable pageable);
}
然后,客户端代码可以执行以下操作:
Pageable topTen = new PageRequest(0, 10);
Page<User> result = repository.findByUsername("Matthews", topTen);
Assert.assertThat(result.isFirstPage(), is(true));
在使用Page
作为返回类型的情况下,我们不会触发实际查询的计数投影,因为我们需要找出总共有多少元素来计算元数据。除此之外,请确保您实际为PageRequest
配备了排序信息,以获得稳定的结果。否则,您可能会触发查询两次,并获得不同的结果,即使底层的数据没有更改。
发布于 2016-02-08 16:50:11
如果您使用的是Java8和Spring Data 1.7.0,如果您希望将@Query
批注与设置最大结果相结合,则可以使用默认方法:
public interface UserRepository extends PagingAndSortingRepository<User,Long> {
@Query("from User u where ...")
List<User> findAllUsersWhereFoo(@Param("foo") Foo foo, Pageable pageable);
default List<User> findTop10UsersWhereFoo(Foo foo) {
return findAllUsersWhereFoo(foo, new PageRequest(0,10));
}
}
发布于 2015-02-11 07:54:49
有一种方法可以提供"a setMaxResults(n) by annotation“的等价物,如下所示:
public interface ISomething extends JpaRepository<XYZ, Long>
{
@Query("FROM XYZ a WHERE a.eventDateTime < :before ORDER BY a.eventDateTime DESC")
List<XYZ> findXYZRecords(@Param("before") Date before, Pageable pageable);
}
当可分页作为参数发送时,这应该会起到作用。例如,要获取前10条记录,您需要将可分页设置为此值:
new PageRequest(0, 10)
https://stackoverflow.com/questions/9314078
复制相似问题