【JAVA】SpringBoot + mongodb 分页、排序、动态多条件查询及事务处理
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class YourService {
@Autowired
private MongoTemplate mongoTemplate;
public Page<YourEntity> dynamicFindPaging(Map<String, Object> filter, int page, int size, String sortField, boolean isAsc) {
Query query = new Query();
if (filter != null) {
filter.forEach(query::addCriteria);
}
Sort.Direction direction = isAsc ? Sort.Direction.ASC : Sort.Direction.DESC;
if (sortField != null) {
query.with(Sort.by(direction, sortField));
}
return mongoTemplate.find(query.with(PageRequest.of(page, size)), YourEntity.class);
}
public List<YourEntity> dynamicFind(Map<String, Object> filter, String sortField, boolean isAsc) {
Query query = new Query();
if (filter != null) {
filter.forEach(query::addCriteria);
}
Sort.Direction direction = isAsc ? Sort.Direction.ASC : Sort.Direction.DESC;
if (sortField != null) {
query.with(Sort.by(direction, sortField));
}
return mongoTemplate.find(query, YourEntity.class);
}
public YourEntity save(YourEntity entity) {
return mongoTemplate.save(entity, YourEntity.class);
}
public void deleteById(String id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, YourEntity.class);
}
// 事务处理方法
public void performTransaction(List<YourEntity> entities) {
mongoTemplate.execute(mongoOperations -> {
for (YourEntity entity : entities) {
mongoOperations.save(entity, YourEntity.class);
}
return null;
});
}
}
class YourEntity {
// 实体类属性和方法
}
这个代码示例展示了如何在Spring Boot项目中使用MongoDB进行分页、排序、动态查询以及事务处理。dynamicFindPaging
方法用于分页查询,dynamicFind
方法用于排序查询,它们接受过滤条件、排序字段和排序方向。save
方法用于保存实体,deleteById
用于根据ID
评论已关闭