我使用 MongoRepository 将 Spring Data 与 MongoDB 一起使用。
我想知道是否可以使用查询注释通过过滤器进行删除。我一直在寻找here和google,但找不到任何文档。
我使用 MongoRepository 将 Spring Data 与 MongoDB 一起使用。
我想知道是否可以使用查询注释通过过滤器进行删除。我一直在寻找here和google,但找不到任何文档。
@Query(value="{'id' : $0}", delete = true)
public Person deleteById (String id);
也许您可以使用存储库删除查询。这是文档中的一个示例:
public interface PersonRepository extends MongoRepository<Person, String> {
List <Person> deleteByLastname(String lastname);
Long deletePersonByLastname(String lastname);
}
使用返回类型 List 将在实际删除它们之前检索并返回所有匹配的文档。数字返回类型直接删除匹配的文档,返回删除的文档总数。
不幸的是,spring data 没有提供任何基于查询删除文档的方法。并且@Query
注释仅用于查找文档。
您可以做的是实现一个自定义存储库,该存储库根据您的需要删除文档。
如何删除查询中的 id 列表?
@Query(value="{idList : $0}", delete = true)
试试这个,它对我有用。
@Repository
public interface DepartmentDao extends MongoRepository<Department, String> {
@DeleteQuery
void deleteByDepartment(String department);
}
或者
@Query(value="{'_id' : ?0}", delete = true)
public void deleteById(String id);
存储库:
@Component
public interface SomeRepository extends MongoRepository<SomeObject, String> {
@Query("{ '_id' : ?0 }")
SomeObject findById(String _id);
}
某些类中的代码:
@Autowired
private SomeRepository pRepo;
public void delete(String id) {
pRepo.delete(pRepo.findById(id));
}