首页 > 解决方案 > 如何让 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 来获取数据。

标签: springspring-bootspring-dataspring-rest

解决方案


我找到了自己问题的答案。

我只需要覆盖 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


推荐阅读