感觉最好还是编写一个自定义控制器,而不是在这里使用Spring Data REST,因为您基本上需要两种资源:一种用于添加链接或返回现有资源,另一种用于通过哈希来检索原始URI。
在第一种方法中,您只需要调用存储库方法findByLongURL(…)
并使用获得的URL
实例(如果您有结果),或采取第二步来实际创建哈希并保存URL
实例思想存储库。第二个资源基本上只是调用您已经存在的方法。
这很简单,也很容易消化。
如果您需要将前一种方法的实现作为原子操作,则需要手动实现存储库查询方法(有关阅读参考文档中相关部分的一般说明):
class UrlRepositoryImpl implements UrlRepositoryCustom {
private final MongoOperations operations;
public UrlRepositoryImpl(MongoOperations operations) {
this.operations = operations;
}
@Override
public URL findOrInsert(String source) {
// What to find?
Query query = Query.query(Criteria.where("longURL").is(source);
// What to write if nothing can be found
Update update = new Update()
.setOnInsert("longURL", source)
.setOnInsert("hash", calculatedHash);
FindAndModifyOptions options = new FindAndModifyOptions.options()
.returnNew(true) // returns the document insert (if so)
.upsert(true); // insert document if it doesn't exist
return operations.findAndModify(query, update, options, URL.class);
}
}
如您所见,这涉及处理一些较低级别的细节(尽管可以通过使用静态导入来减少冗长程度),但基本上可以为您提供原子操作。