为什么没有使用Spring Data JPA设置版本属性?

想知道Spring Data REST中的@Version注释如何用于ETag,我没有看到ETag由于某种原因填充

 @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); 

但是,给定实体和以下配置,我仍然为版本获取null。 我的申请表如下

 @SpringBootApplication @EnableEntityLinks @EnableJpaAuditing public class GabbarSinghApplication 

Rest Repository如下

 @RepositoryRestResource(collectionResourceRel = "venue", path = "venues") public interface VenueRepository extends JpaRepository { 

虽然我还没有用头文件等测试这些方法,但http://localhost:8080/workshops上的一个简单的POST请求因为从版本属性的值获取ETag头值时的空指针exception而给出500

更新

移动到实体的@ javax.persistence.Version,我仍然没有在响应头中获得ETag标头。

这是一个失败的unit testing

  @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 httpEntity = new HttpEntity(taj, headers); ResponseEntity response = restTemplate.exchange(BASE_LOCATION + VENUES_ENDPOINT, HttpMethod.POST, httpEntity, new ParameterizedTypeReference() { }); assertTrue("Response should contain ETag header", null != response.getHeaders().getETag()); 

这个断言失败了。

使用Spring Data JPA,您需要使用@javax.persistence.Version@org.springframework.data.annotation.Version是用于其他Spring Data模块的注释。

我遇到了同样的问题,经过几个小时和几个小时后,我意识到以下事情让我得到启示= P.

  1. Spring Data Rest仅在版本2.3.0之后为乐观并发控制提供ETag支持。 查看大约一年前发布的此错误 。 以前版本的Spring Data Rest不会填充ETag标头。
  2. 对于Spring Boot应用程序(我们的例子),您需要使用Spring Boot 1.3.0.BUILD-SNAPSHOT或更高版本,以便能够设置依赖于Spring Data Rest 2.4.1的spring-boot-starter-data-rest。 (高于2.3.1,这正是我们所需要的:P)。

在我的情况下,我使用的是Spring Boot 1.2.7,每当我安装spring-boot-starter-data-rest依赖时,我最终得到了没有ETag支持的Spring Data Rest 2.2.0。 在我的项目中升级Spring Boot并重新安装依赖项后,我的REST API开始检索ETag header = D.