Java实战:Spring Boot集成MongoDB
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.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private MongoTemplate mongoTemplate;
public void createUser(User user) {
mongoTemplate.save(user, "users");
}
public List<User> getAllUsers() {
return mongoTemplate.findAll(User.class, "users");
}
public User getUserById(String id) {
Query query = new Query(Criteria.where("id").is(id));
return mongoTemplate.findOne(query, User.class, "users");
}
public void updateUser(String id, User user) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.upsert(query, user, "users");
}
public void deleteUser(String id) {
Query query = new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query, User.class, "users");
}
}
这段代码提供了一个简单的用户服务类,用于与MongoDB数据库进行交互。它展示了如何使用Spring Data MongoDB的MongoTemplate
来执行基本的CRUD操作。这个类可以作为集成MongoDB到Spring Boot项目中的参考。
评论已关闭