如何让Spring的Data Rest Repository按名称而不是id来检索数据

问题描述 投票:0回答:2

我使用spring-boot-starter-data-rest中的Spring Data的Rest Repositories,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来获取数据。

spring spring-boot spring-data spring-rest
2个回答
0
投票

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

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


-1
投票

如果您希望按名称查询项目并希望它按ID进行查询,则应确保名称也是唯一的。如果所有对象具有相同的名称,则无法按名称标识显式对象,对吧?

有了jpa,你可以这样做:

@NotNull
@Column(name="name",nullable=false,unique=true)
private String name;
© www.soinside.com 2019 - 2024. All rights reserved.