在遵循https://spring.io/guides/gs/accessing-mongodb-data-rest/ 上非常有用的教程之后,我正在尝试创建一个链接缩短器应用程序。我编写了一个 URL 类(使用 id
、longURL
和 hash
属性)和 URLRepository 类(目前,仅使用 findByHash
方法,如演示中所示)。请注意,我所说的“散列”指的是由尚未实现的方法生成的随机短字符串,而不是像 MD5 这样的实际散列函数。只是调用一个独立的 generateHash(String URL)
例如
我可以使用 Spring 提供的 REST 接口(interface)向数据库中添加新条目,也可以获取它们。但是,我想让应用程序自己生成散列,并在存储它之前进行一些检查和处理——主要是检查 URL 是否尚未存储,在这种情况下,它只会返回现有的散列。
我想我必须延长 SimpleMongoRepository
的 <S extends T> List<S> save(Iterable<S> entites);
我的 MongoRepository
下的方法(由 URLRepository
扩展)类,但我不确定该怎么做。我还看到了 insert
方法,我不知道应该使用哪种方法
网址.java
public class URL {
@Id private String id;
private String longURL;
private String hash;
public String getLongURL() {
return longURL;
}
public void setLongURL(String longURL) {
this.longURL = longURL;
}
public String getHash() {
return hash;
}
public void setHash(String Hash) {
this.hash = Hash;
}
}
URLRepository.java
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.util.Assert;
@RepositoryRestResource(collectionResourceRel = "urls", path = "urls")
public interface URLRepository extends MongoRepository<URL, String> {
List<URL> findByHash(@Param("hash") String hash);
}
最佳答案
感觉你最好编写一个自定义 Controller 而不是在这里使用 Spring Data REST,因为你基本上需要两种资源:一种用于添加链接或返回现有的,另一种用于通过其哈希检索原始 URI .
在第一种方法中,您只需调用存储库方法 findByLongURL(…)
并使用获得的 URL
实例(如果您有结果或采取第二步)实际上创建散列并保存 URL
实例思想存储库。第二个资源基本上只是调用您已经存在的方法。
这很简单,也很容易理解。
如果您需要将前一种方法的实现作为原子操作,则需要手动实现存储库查询方法(有关一般说明,请阅读 reference documentation 中的相关部分):
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);
}
}
如您所见,这涉及处理一些较低级别的细节(尽管可以通过使用静态导入来减少冗长),但基本上为您提供了一个原子操作。
关于spring - 在将它们添加到 MongoDB 之前,如何在 Spring Data 中处理插入请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31827532/