我正在尝试将Spring-Data-JPA合并到我的项目中.让我困惑的一件事是如何通过注释实现setMaxResults(n)?
例如,我的代码:
public interface UserRepository extends CrudRepository<User , Long>
{
@Query(value="From User u where u.otherObj = ?1 ")
public User findByOhterObj(OtherObj otherObj);
}
Run Code Online (Sandbox Code Playgroud)
我只需one (and only one)要从otherObj 返回用户,但我找不到一种方法来注释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
Run Code Online (Sandbox Code Playgroud)
)
我找到了一个链接:https://jira.springsource.org/browse/DATAJPA-147,我试过但失败了.现在似乎不可能?为什么Spring-Data中没有内置这么重要的功能?
如果我手动实现此功能:
public class UserRepositoryImpl implements UserRepository
Run Code Online (Sandbox Code Playgroud)
我必须实现大量的预定义方法 …
我需要从DB只带一个结果.我怎么能用JPA做到这一点?
Select top 1 * from table
Run Code Online (Sandbox Code Playgroud)
我试过了
"从表格中选择t"
query.setMaxResults(1);
query.getSingleResult();
Run Code Online (Sandbox Code Playgroud)
但没有奏效.还有其他想法吗?
JpaSpecificationExecutor附带的方法是不够的,它们都没有给我我想要的东西:
Page<T> findAll(Specification<T> spec, Pageable pageable)
List<T> findAll(Specification<T> spec)
List<T> findAll(Specification<T> spec, Sort sort)
Run Code Online (Sandbox Code Playgroud)
第一种方法执行分页查询和计数查询.接下来的2个根本不执行分页.我需要的是以下之一:
Slice<T> findAll(Specification<T> spec, Pageable pageable)
List<T> findAll(Specification<T> spec, Pageable pageable)
Run Code Online (Sandbox Code Playgroud)
通过不扩展JpaSpecificationExecutor,我能够执行两个查询,但计数查询也是如此.在我的情况下,必须避免计数查询,因为它非常昂贵.问题是如何?