【问题标题】:How do I get Spring's Data Rest Repository to retrieve data by its name instead of its id如何让 Spring 的 Data Rest Repository 按名称而不是 id 检索数据
【发布时间】:2018-11-23 02:32:52
【问题描述】:

我正在使用来自 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 来获取数据。

【问题讨论】:

    标签: spring spring-boot spring-data spring-rest


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      如果你想通过名称查询项目并希望它像通过id查询一样执行,你应该确保名称也是唯一的。如果所有对象都具有相同的名称,你不能通过名称来识别明确的对象,对吧?

      使用 jpa 你可以这样做:

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

      【讨论】:

      • 没错,但这并不能回答问题。另外,我使用的是 Couchbase 数据库,这里没有使用 JPA。
      猜你喜欢
      • 2023-03-09
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2018-05-22
      相关资源
      最近更新 更多