簡體   English   中英

如何獲取Spring的Data Rest信息庫以按其名稱而不是其ID檢索數據

[英]How do I get Spring's Data Rest Repository to retrieve data by its name instead of its 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

如果要按名稱查詢項目並希望其按ID查詢執行,則還應確保名稱也是唯一的。如果所有對象都具有相同的名稱,則無法按名稱標識顯式對象,對嗎?

使用jpa,您可以像這樣:

@NotNull
@Column(name="name",nullable=false,unique=true)
private String name;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM