I have a class person having property first_name of string type, Now I want to define a find method in PersonRepository which can find all person having first name equals to a string. I am adding this method in Person repository like this.

List<Person> findByFirst_name(String first_name) but I am getting error saying that there is no property first in person class. I already define so many find method but those properties does not contains _ so I can easily define those findBy methods. This problem I faced only with properties having _ (underscores) in name string. For some reasons I can not change first_name to fisrtName, Is there anything I am doing wrong? How to create findBy Method for properties having _ is this a special case?

here is my code. Person.java

@Document(collection="person")
public class Person {
    
    @Id
    private String id;
    private String first_name;
    private String last_name;
    private String gender;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getFirst_name() {
        return first_name;
    }
    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }
    public String getLast_name() {
        return last_name;
    }
    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
}

PersonRepository.

public interface PersonRepository extends MongoRepository<Person, String>{
    
    List<Person> findByGender(String gender);
    List<Person> findByFirst_name(String first_name); // throwing error (No property first found for type Person!)
    
}

Error: Caused by: org.springframework.data.mapping.PropertyReferenceException: No property first found for type Person!

1

There are 1 best solutions below

2
jalil On

You have Two ways to solve this issue:

  1. Make your entity fields camelCase
  2. Skip the underscore in your first_name by doubling the underscore like first__name so it should look like findByFirst__name(String first_name);