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<Company> 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<Company> class1); public void insert(Company company); }
總結:與關系型數據庫的連接一樣,沒有什麼區別。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!