How to write custom query in Mongo Spring Data JPA

7.7k views Asked by At
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;   

 @Repository    
    public interface PersonRepository extends MongoRepository<Person, String> {

            @Query("{ 'firstname' : ?0 }")
            List<Person> findByFirstname(String firstname);

        }

I am using spring data jpa with MongoDB. I am able to save, delete or retrieve (all records) using repository.

I am trying to retrieve record based on a property value. (Custom Query shown above). This does not work.

Can someone help me in finding out how to write custom Queries in MongoRepository where I can pass a column value and get the matching rows.

EDIT:

Adding Code.

@Document/*(collection = "person")*/
public class Person {

    @Id
    private String id;

    private String firstName;

    private String lastName;

    private Address address;
          // gettters and setters
}

@Service
public class PersonServiceImpl{

          @Autowired
    private PersonRepository personRepository;

          public Person findPersonByFirstName(String firstName) {

        List<Person> person = personRepository.findAllByFirstName(firstName);

        System.out.println("** Data Retrieved **" );

        return person.get(0);
    }
}
1

There are 1 answers

7
František Hartman On

You don't need a custom query for this kind of query.

Following should just work (provided your field in Person class is "firstname" - is that righ?)

List<Person> findAllByFirstname(String firstname);

Does your query work from a mongo console?