Search code examples
spring-dataspring-data-mongodbspring-data-restspring-repositories

How to build a search endpoint in spring data MongoRepository


I'm trying to access the mongodb data layer using spring data MongoRepository. So in here im able do the basic CRUD operations using the repository endpoint but failed to do the custom search.

Model class :

@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
}

The repository :

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

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

When i'm trying using this code i get the following error :

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

Is this the correct way to implement this? or what is the resolve for this issue im getting?


Solution

  • The name of the method is important, it tells Spring Data MongoDB how to build the query. You have named the method findByName, so Spring Data MongoDB is trying to create a query against a property called name, but you don't have any property named simply name in your Merchant collection.

    To query against Merchant.businessName your method should be:

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