我有一個擴展CrudRepository的接口,並且每次使用已存在的鍵保存對象時,它都會用新的鍵覆蓋現有對象。我如何覆蓋save
,以便它檢查具有該密鑰的對象是否已經存在?CRUD儲存庫:覆蓋保存到實現存在
我已經嘗試以下,但它沒有工作:
public interface CustomRepo {
public Channel save(Channel channel);
}
public class RepositoryImpl implements CustomRepo {
@Autowired
private DynamoDBMapper mapper;
public Channel save(Channel channel){
channel.setId(UUID.randomUUID().toString());
DynamoDBSaveExpression saveExpression = new DynamoDBSaveExpression();
Map<String, ExpectedAttributeValue> expectedAttributes =
ImmutableMap.<String, ExpectedAttributeValue>builder()
.put(channel.getUrl(), new ExpectedAttributeValue(false))
.put(channel.getTitle(), new ExpectedAttributeValue(false))
.build();
saveExpression.setExpected(expectedAttributes);
saveExpression.setConditionalOperator(ConditionalOperator.AND);
try {
mapper.save(channel, saveExpression);
} catch (ConditionalCheckFailedException e) {
System.err.println("Item with URL {} already exists. Cannot overrwrite."+ channel.getUrl());
System.err.println(e.getMessage());
}
return channel;
}
public interface ChannelRepository extends CrudRepository<Channel, String>, CustomRepo {
@EnableScan
List<Channel> findByTitle(String title);
@Override
@EnableScan
List<Channel> findAll();
List<Channel> findByUrl(String url);
}
這是一個很好的答案 - 一個,我可能會使用一些容量。但我特別詢問了重寫save方法來定義我自己的保存邏輯。 – acs254