CrudRepository:返回一个按列排序的结果

时间:2015-02-23 17:39:40

标签: java mysql jpa spring-data

CrudRepository接口是否有办法对具有多行的表进行排序,并简单地返回第一行,例如按时间戳排序只返回最新一行?

public interface ImportReceiptRepository extends CrudRepository<ImportReceipt, Long>
{
    ImportReceipt getOneByImportTypeOrderByTimestampDesc(String importType);
    ImportReceipt findOneByImportTypeOrderByTimestampDesc(String importType);
}

findOneBy ...和getOneBy ... throw:

org.springframework.dao.IncorrectResultSizeDataAccessException: result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:395)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:216)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:105)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy109.findOneByImportTypeOrderByTimestampDesc(Unknown Source)
at edu.ucdavis.dss.dw.services.DefaultImportReceiptService.getLatestOneByImportType(DefaultImportReceiptService.java:26)
...

或者换句话说,CrudRepository相当于:

SELECT * FROM ImportReceipts ORDER BY timestamp DESC LIMIT 0,1;

1 个答案:

答案 0 :(得分:8)

Bludream的答案来自setMaxResults for Spring-Data-JPA annotation? ......有答案。

语法是“findFirst”或“findTop10”,尽管它仍然返回一个列表。

List<ImportReceipt> findFirstByImportTypeOrderByTimestampDesc(String importType);

我认为List总是大小()0或1。