SpringBoot MongoTemplate使用详解
import org.springframework.beans.factory.annotation.Autowired;
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.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
@Service
public class MyMongoService {
@Autowired
private MongoTemplate mongoTemplate;
public void insert(MyDocument document) {
mongoTemplate.insert(document, "myCollection");
}
public MyDocument findById(String id) {
return mongoTemplate.findById(id, MyDocument.class, "myCollection");
}
public void update(String id, MyDocument newDocument) {
Query query = new Query(Criteria.where("id").is(id));
Update update = new Update().set("field1", newDocument.getField1()).set("field2", newDocument.getField2());
mongoTemplate.updateFirst(query, update, MyDocument.class, "myCollection");
}
public void deleteById(String id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, MyDocument.class, "myCollection");
}
}
class MyDocument {
private String id;
private String field1;
private String field2;
// getters and setters
}
这个代码示例展示了如何使用Spring Boot的MongoTemplate
来执行MongoDB的基本操作,包括插入、查询、更新和删除。这个类可以被注入到Spring的应用上下文中,并用于与MongoDB数据库交互。
评论已关闭