想知道 Spring Data REST 中的 @Version
注释是如何用于 ETags 的,但由于某种原因我没有看到 ETags 填充
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Venue implements Serializable {
private static final long serialVersionUID = -5516160437873476233L;
private Long id;
...
// other properties
private Long version;
private Date lastModifiedDate;
// getters & setters
@JsonIgnore
@LastModifiedDate
public Date getLastModifiedDate() {
return lastModifiedDate;
}
@Version
@Column
public Long getVersion() {
return version;
}
按照文档,这应该会给我一个 Etag 值吗?如库中的片段所示
protected HttpHeaders prepareHeaders(PersistentEntity<?, ?> entity, Object value) {
// Add ETag
HttpHeaders headers = ETag.from(entity, value).addTo(new HttpHeaders());
// Add Last-Modified
AuditableBeanWrapper wrapper = getAuditableBeanWrapper(value);
但是,鉴于实体和以下配置,我仍然得到版本为空。 我的应用程序有以下
@SpringBootApplication
@EnableEntityLinks
@EnableJpaAuditing
public class GabbarSinghApplication
而Rest Repository如下
@RepositoryRestResource(collectionResourceRel = "venue", path = "venues")
public interface VenueRepository extends JpaRepository<Venue, Long> {
虽然我还没有使用标题等测试这些方法,但在 http://localhost:8080/workshops
上的简单 POST 请求会给出 500
因为从版本属性的值获取 ETag header 值时出现空指针异常。
更新
实体已移至 @javax.persistence.Version,但我仍然没有在响应 header 中获得 ETag header 。
这是一个失败的单元测试
@Before
public void setUp() throws Exception {
XStream xstream = new XStream();
ObjectInputStream in = xstream.createObjectInputStream(venuesXml.getInputStream());
leela = (Venue) in.readObject();
paul = (Venue) in.readObject();
taj = (Venue) in.readObject();
LOGGER.debug("Initialised Venues from xml file {}", venuesXml.getFilename());
}
@Test
public void testEtagHeaderIsAutoGeneratedOnResourceCreation() {
final HttpEntity<Venue> httpEntity = new HttpEntity<Venue>(taj, headers);
ResponseEntity<ResourceSupport> response = restTemplate.exchange(BASE_LOCATION
+ VENUES_ENDPOINT, HttpMethod.POST, httpEntity,
new ParameterizedTypeReference<ResourceSupport>() {
});
assertTrue("Response should contain ETag header", null != response.getHeaders().getETag());
此断言失败。
最佳答案
使用 Spring Data JPA,您需要使用 @javax.persistence.Version
。 @org.springframework.data.annotation.Version
是用于其他 Spring Data 模块的注解。
关于java - 为什么没有使用 Spring Data JPA 设置版本属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31882180/