2015-02-23 86 views
2

CrudRepository接口是否有一種方法來對具有多行的表進行排序並簡單地返回第一行,例如,按時間戳排序以僅返回最新的行?CrudRepository:返回一個結果,按列排序

兩個findOneBy ...和... getOneBy拋出:

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; 
+0

不知道這是一個重複:這個問題的答案和一個它又指的是具有JPA查詢對象這是一個重複而不是CrudRepository的情況。 – Christopher 2015-02-23 18:28:37

+0

看起來像Bludream從http://stackoverflow.com/questions/9314078/setmaxresults-for-spring-data-jpa-annotation的答案是我正在尋找。語法是「findFirst」或「findTop10」,儘管它仍然返回一個列表。感謝holmis83的幫助,您的鏈接讓我走上了正確的道路。 – Christopher 2015-02-23 18:33:53

+0

啊,我不知道它和「標準」JPA是如此不同。好吧,我學到了一些新東西。 – holmis83 2015-02-23 18:50:05

回答

4

Bludream的計算器,從回答.com/questions/9314078/...有答案。

語法爲「findFirst」或「findTop10」,雖然它仍然返回一個列表。

List<ImportReceipt> findFirstByImportTypeOrderByTimestampDesc(String importType); 

我想名單將永遠是尺寸的()0或1