2016-11-16 281 views
1

我有一个Java应用程序,它使用Spring数据从mongo数据库检索数据。我有一个案例,我想从mongo collection中检索所有对象,其中isDeleted标志设置为false使用spring数据从MongoDB检索数据findAll(示例<S>示例)

我试图使用org.springframework.data.domain.ExampleMatcher,如https://github.com/spring-projects/spring-data-examples/tree/master/mongodb/query-by-example中所述,但它不起作用(返回0条记录)。下面是我的尝试代码片段。

注意:我尝试通过在下面的代码段中添加和删除withIgnoreNullValues()。它没有帮助。

public List<Adns> getAll(){ 
     Adns matcherObject = new Adns(); 
     matcherObject.setDeleted(false); 
     ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues(). 
           withMatcher("isDeleted", exact()); 
     Example<Adns> example = Example.of(matcherObject,matcher); 
     return adnsRepository.findAll(example); 
    } 

我能够检索所有没有成功布尔过滤器的对象。以下是工作代码。

public List<Adns> getAll(){ 
    return adnsRepository.findAll(); 
} 

下面是类UML:
enter image description here

+1

你试过'findByDeletedIsFalse()'吗? – chrylis

+0

感谢您的快速回复。但是,我不确定您的建议是什么?我没有看到像org.springframework.data.mongodb.repository.MongoRepository提供的任何方法,可以扩展更多吗? – Dhyan

+1

阅读文档。只需在你的'AdnsRepository'上定义*这个方法,它就会为你创建。 – chrylis

回答

1

你需要你的资料库界面上创建方法声明findByDeletedIsFalse

在运行时,sp​​ring数据会自动找到该接口并为其创建一个实现。这实际上是春季数据的关键特征之一。你可以阅读更多关于query methods in the docs。春季文档非常容易阅读,并且有很多例子。

假设你Adns使用Long作为主ID,并且您正在使用基本CrudRepository提供商,你应该有:有关查询方法生成

public interface AdnsRepository extends CrudRepository<Adns, Long> { 
    // this method declaration is automatically implemented by the spring-data library at runtime. 
    List<Adns> findByDeletedIsFalse(); 
} 

的更多信息: