Spring缓存与春季数据休息库缓存异常保存结果

问题描述:

我有一个Spring Data Rest存储库,我想使用Spring缓存。Spring缓存与春季数据休息库缓存异常保存结果

当没有错误时,缓存按预期工作。但是,如果保存的结果是验证异常,则即使未将实体写入数据库,实体也会被缓存。

SDR储备库

@RepositoryRestResource(collectionResourceRel = "businessUnits", path = "businessUnits") 
public interface BusinessUnitRepository extends JpaRepository<BusinessUnit, UUID> { 

@Override 
@Cacheable(value = "lookups", cacheManager = "vaultCache") 
BusinessUnit findOne(final UUID id); 

@Override 
@CacheEvict(value = "lookups", cacheManager = "vaultCache", allEntries = true, beforeInvocation = true) 
BusinessUnit save(BusinessUnit entity); 

如果我后下一个新的业务部门的消息体是正确保存。第一个获取记录的GET按预期击中数据库,并且后续的GET来自缓存。

{ 
"name": "Test_Business_2", 
"effectiveDate": "2019-12-16T11:11:11.111+0000", 
"expirationDate": "2020-12-16T11:11:11.111+0000", 
"businessUnitType": "/businessUnitTypes/38faf33c-5454-4245-bc69-2b31e510fa6b" 
} 

BusinessUnit实体在effectiveDate字段上具有非空值。

@NotNull 
@Column(name = "effective_date") 
private Timestamp effectiveDate; 

当我用空effectiveDate PATCH业务单位。响应是错误,会记录异常并且数据库不会更新。

{ 
"effectiveDate": null 
} 

当我查询数据库,我看到记录没有更新

NAME   EFFECTIVE_DATE  EXPIRATION_DATE 
Test_Business_2,2019-12-16 06:11:11,2020-12-16 06:11:11 

然而,当我做了businessUnits端点的GET。数据库不会读取记录,并返回null effectiveDate。

{ 
"createDate": "2017-02-20T13:38:00.386+0000", 
"lastModifiedDate": "2017-02-20T13:38:00.386+0000", 
"effectiveDate": null, 
"expirationDate": "2020-12-16T11:11:11.111+0000", 
"name": "Test_Business_2", ... 

因此,似乎引起异常被抛出的数据被存储在缓存中。

我需要更改什么,以便在保存时数据库未更新时,值不会保存在缓存中?

我感谢任何帮助或建议。谢谢。

+0

我还没有找到解决我的问题,但我找到了解决办法。在我看到错误的情况下抛出异常,但缓存没有被驱逐。在处理异常的方法中,我可以编程清除缓存。 Cache cache = cacheManager.getCache(“lookups”); cache.clear(); 然后缓存被清除,并且不包含“异常”值。 –

您缓存的key和您驱逐的key不匹配。您需要定义如何从BusinessUnit获得ID,例如:

@CacheEvict(key = "#entity.id" 

或提供KeyGenerator能够理解你的域模型。

+0

无论beforeInvocation设置如何,我都会得到相同的结果。我试过将它设置为true,并将其设置为false。 –

+0

对不起,我误解您的注释 – OrangeDog

+0

@EricSmith更新 – OrangeDog