Java连接MongoDB进行增删改查的操作
1.创建数据库的连接,进行增删改查
(分别为接口和实现类)
package com.dao;
import java.util.List;
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.Repository;
import com.bean.Company;
@Repository
public class RepositoryImpl implements AbstractRepository {
@Autowired
private MongoTemplate mongoTemplate;
// 查询所有数据
public List> findAll(Class> entity) {
return mongoTemplate.findAll(entity);
}
// 更新数据
public Company findOne(String id, Class> entity) {
return (Company) mongoTemplate.findOne(new Query(Criteria.where("id")
.is(id)), entity);
}
// 添加到数据库
public void updateEntity(Company company) {
mongoTemplate.save(company);
}
// 删除选中的数据
public void delete(String id, Class class1) {
Criteria criteria = Criteria.where("id").in(id);
if (criteria != null) {
Query query = new Query(criteria);
if (query != null && mongoTemplate.findOne(query, class1) != null)
mongoTemplate.remove(mongoTemplate.findOne(query, class1));
}
}
//增加到数据库
public void insert(Company company) {
mongoTemplate.insert(company);
}
}
package com.dao;
import java.util.List;
import com.bean.Company;
public interface AbstractRepository {
public List> findAll(Class> entity);
public Company findOne(String id,Class> entity);
public void updateEntity(Company company);
public void delete(String id, Class class1);
public void insert(Company company);
}
总结:与关系型数据库的连接一样,没有什么区别。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!