2014-04-03 31 views
1

使用mongodb的彈簧數據,如何指定存儲庫方法的返回類型以包含文檔中的特定屬性? 例如:springdata mongo存儲庫方法返回特定文檔屬性列表

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

庫:如預期,並獲取唯一的名字從文檔屬性

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

以上findAllNames作品。然而,彈簧數據返回對象是Foo對象的string表示,該對象具有值和剩餘屬性爲空的id和name屬性。 而不是Foo對象,我需要取List<String>這代表名字。

回答

1

截至目前,我使用自定義界面來實現這一點。將Spring數據存儲庫接口中的findAllNames()方法移至我的自定義接口

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 
} 
} 
+0

嗨,還有其他方法嗎? – TimSchwalbe