spring - 如何让 Spring 的 Data Rest Repository 按名称而不是 id 检索数据
问题描述
我正在使用来自 spring-boot-starter-data-rest 的 Spring Data 的 Rest 存储库,其中 Couchbase 用作下划线 DBMS。
我的对象的 Pojo 就是这样设置的。
@Document
public class Item{
@Id @GeneratedValue(strategy = UNIQUE)
private String id;
@NotNull
private String name;
//other items and getters and setters here
}
并假设该项目的 id 为“xxx-xxx-xxx-xxx”,名称为“testItem”。问题是,当我想访问该项目时,我需要通过 访问/items/testItem
,但它可以通过 访问/items/xxx-xxx-xxx-xxx
。
如何使用其名称而不是其生成的 id 来获取数据。
解决方案
我找到了自己问题的答案。
我只需要覆盖 EntityLookup 的配置。
@Component
public class SpringDataRestCustomization extends RepositoryRestConfigurerAdapter {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.withEntityLookup().forRepository(UserRepository.class).
withIdMapping(User::getUsername).
withLookup(UserRepository::findByUsername);
}
}
在这里找到了信息,尽管方法名称略有变化。 https://github.com/spring-projects/spring-data-examples/tree/master/rest/uri-customization
推荐阅读
- python - 根据索引列表从 numpy 数组中获取和替换值
- excel - 创建数据透视表
- python - Python 3.7 在类型注释上抛出 NameError 但我不想导入定义它的模块
- ios - SwiftUI Preview Canvas 与核心数据一起崩溃
- tensorflow - 加载 Tensorflow 数据集时,“as_supervised”布尔表达式有什么用?
- c++ - 为什么不是所有的字符串字符都被访问?
- java - JavaFX 无法从另一个线程更改场景
- python - 密集层权重矩阵的维数
- javascript - 从节点对 Active Directory 进行间歇性身份验证
- jsonata - 如果在 JSON (JSONata) 中找不到值,如何抛出错误