如何在Spring Data MongoRepository中构建搜索端点

时间:2019-01-24 08:03:53

标签: spring-data spring-data-mongodb spring-data-rest spring-repositories

我正在尝试使用Spring数据MongoRepository访问mongodb数据层。因此,这里无法使用存储库端点执行基本的CRUD操作,但无法执行自定义搜索。

模型类:

@Document(collection = "merchant")
public class Merchant {

 @Id
 private String id;
 private Long zohoAccountRefId;
 private String businessId;
 private String businessName;
 private String businessAddress;
 private String businessPhone;
 private String description;
 private String businessEmail;
 private String accountType;
 private BusinessOwner businessOwner;
 private List<Product> products;
 private List<Plugin> plugins;
 private List<Service> services;
 @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
 private Date dateCreated;

 //getters and setters
}

存储库:

@RepositoryRestResource(collectionResourceRel = "account",path = "account")
public interface MerchantRepository extends MongoRepository<Merchant,String> {

  @RestResource(path = "businessName",rel = "businessName")
  List<Merchant> findByName(@Param("businessName") String businessName);
 }

当我尝试使用此代码时,出现以下错误:

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type Merchant!

这是实现此目标的正确方法吗?或解决此问题的解决方案是什么?

1 个答案:

答案 0 :(得分:2)

方法的名称很重要,它告诉Spring Data MongoDB如何构建查询。您已将方法命名为findByName,因此Spring Data MongoDB尝试针对名为name的属性创建查询,但在Merchant集合中没有名为name的任何属性

要针对Merchant.businessName查询,您的方法应为:

List<Merchant> findByBusinessName(@Param("businessName") String businessName);