Frage

using spring data for mongodb, how do I specify the return type of the repository method to include a particular property from the document? Ex:

@Document (collection = "foo")
class Foo {
   String id
   String name
   ... many more attributes
}

repository:

interface FooRepository extends MongoRepository<Foo, String> {
   @Query { value = "{}", fields = "{'name' : 1}" }
   List<String> findAllNames()
}

Above findAllNames works as expected and fetches only name property from the document. However spring data returned object is a string representation of Foo object which has id and name properties with values and remaining attributes as null. Instead of Foo objects, I need to fetch List<String> which represents names.

War es hilfreich?

Lösung

As of now, I used a custom interface to achieve this. Moved the findAllNames() method from Spring data repository interface to my custom interface

interface FooRepositoryCustom {
    List<String> findAllNames()
}
interface FooRepository extends MongoRepository<Foo, String>, FooRepositoryCustom {
}

@Component
class FooRepositoryImpl implements FooRepositoryCustom {
   @Autowired
   MongoOperations mongoOperations;

  List<String> findAllNames() {
    //using mongoOperations create the query and execute. Return the property values from document
 }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top