我正在開發使用spring-boot-starter-data-jpa-1.5.2.RELEASE的spring-boot REST服務器。我有以下POJO類層次結構。首先是基類實體:spring-boot/spring-data-jpa通過日期字段自定義查詢過濾返回結果沒有過濾
@javax.persistence.Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Entity implements Serializable {
@Id
@Column(name = "id", nullable = false, length = 48)
public String id = UNINITIALIZED_ID;
/**
* The timestamp for when this entity was last updated.
*/
@Column(columnDefinition = "timestamp with time zone")
@Temporal(TemporalType.TIMESTAMP)
public Date updateTimestamp = new Date();
}
接下來的具體子類的病人:
@javax.persistence.Entity
@Table(indexes={@Index(columnList="updateTimestamp")})
public class Patient extends Entity {
...
}
我定義我PatientRepository界面的自定義方法如下,以獲取患者的updateTimestamp是指定的時間戳之後:
@RepositoryRestResource(collectionResourceRel = "patients", path = "patients")
public interface PatientRepository extends JpaRepository<Patient, String> {
List<Patient> findByUpdateTimestampAfter(@DateTimeFormat(iso=DateTimeFormat.ISO.DATE_TIME)@Param("after")Date after);
}
對於一些未知的原因由updateTimestamnp過濾器時,我發出了通過先進的REST客戶端,瀏覽器插件,下面的GET請求不工作:
// url example. DateFormat matches @DateTimeFormat on param in query method.
GET http://127.0.0.1:8090/patients?after=2030-01-10T00:00:00.000-05:00
我只期望有updateTimestamp之後要重新指定的時間戳,但我得到的是資源集合中的所有實體,而不是那些實體。
我已經在spring-boot上打開了DEBUG日誌記錄。下面是我不知道的東西是一個問題:
2017-05-18 10:15:56.127 DEBUG 5292 --- [ main] o.s.d.j.r.query.JpaQueryFactory : Looking up query for method findByUpdateTimestampAfter
2017-05-18 10:15:56.132 DEBUG 5292 --- [ main] o.s.d.jpa.repository.query.NamedQuery : Looking up named query Patient.findByUpdateTimestampAfter
2017-05-18 10:15:56.133 DEBUG 5292 --- [ main] o.s.d.jpa.repository.query.NamedQuery : Did not find named query Patient.findByUpdateTimestampAfter
基於從@pvpkiran我wroite以下斯波克集成測試和很好的建議表明,aftergetting日期來分析我的PatientRepository.findByUpdateTimestampAfter方法按預期工作:
@SpringBootTest(classes = com.altran.medmap.server.Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional
class PatientRepositorySpec extends Specification {
@Autowired
PatientRepository patientRepository;
@Bean
@Unroll
def 'Should GET #size patients whose updateTimestamp is after: #after'({
given:
DateFormat dateFormat = new SimpleDateFormat('MMM d, yyyy h:mm:ss a');
Date afterx = dateFormat.parse(after);
when:
List<Patient> result = patientRepository.findByUpdateTimestampAfter(after);
then:
result.size() == size;
where: 'result size matches expected'
after | size
'Jan 1, 2016 00:00:00 AM' | 2
'Jan 1, 2030 00:00:00 AM' | 0
}
}
REST API仍然返回所有實體的事實仍然是一個未解決的謎團。不是我在Repository接口中的查詢方法參數中指定了@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME),並且在靜態URL中使用了相同的格式。有什麼建議去哪裏?
當你說不工作,這是否意味着沒有記錄被提取或你是否有任何異常。你有在DB中符合這個標準的記錄嗎? – pvpkiran
非常抱歉。只是更新了我得到的所有實體,而不是指定時間戳後具有updateTimestamp的子集。 –
刪除你的'@ Query'並嘗試。 Spring數據足夠智能,可以通過方法名稱來制定查詢。我認爲問題在於你用'>'比較的方式。所以把這些複雜性留給框架。只需嘗試不用@ Query – pvpkiran