javaspringmongodbmongorepository

Resolve variable name for MongoRepository in Spring


What is the correct method name for variable with _ in MongoRepository.

History.java

@Document(collection = "spring-history")
public class History {
    private Long record_id;

    //getter - setter
}

HistoryRepository.java

public interface HistoryRepository extends MongoRepository<History, String>{
    List<History> findAllByRecordid(Long recordId);
}

I got the following exception

Caused by: org.springframework.data.mapping.PropertyReferenceException: No property recordid found for type History! Did you mean 'record_id'?

I've tried following variable options but none of this working.

List<History> findAllByRecordId(Long recordId);
List<History> findAllByRecord_id(Long recordId);
List<History> findAllByRecord__id(Long recordId);

Solution

  • The exception says that there is No property recordid found for type History!.

    This happens because your repository method written as findAllByRecordid is currently looking for a property recordid inside the History class.

    What you have to do is to chang your History class accordingly; for example, you can change

    private Long record_id;
    

    to

    private Long recordid;
    

    However, since I suppose that record_id is a composed name variable, you should use the camel case convention and name it recordId.

    Following the camel case convention, you have to also change the repository method to List<History> findByRecordId(Long recordId);

    In this case, you have also to annotate the recordId with the @Field annotation in order to map the recordId property to the actual key in the MongoDB BSON document. for further details/information, you can give a look at Mapping annotation overview