我使用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来获取数据。
我找到了自己问题的答案。
我只需要覆盖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;