上海网站建设官方网站,咨询公司名字大全,网站建设10个基本步骤,网站建设为什么需要备案前言 MongoDB#xff08;来自于英文单词“Humongous”#xff0c;中文含义为“庞大” #xff09;是可以应用于各种规模的企业、各个行业以及各类应用程序的开源数据库。基于分布式文件存储的数据库。由C语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoD…前言 MongoDB来自于英文单词“Humongous”中文含义为“庞大” 是可以应用于各种规模的企业、各个行业以及各类应用程序的开源数据库。基于分布式文件存储的数据库。由C语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个高性能开源无模式的文档型数据库是当前NoSql数据库中比较热门的一种。 正文
Spring Boot 对 MongoDB 的数据源操作进行了封装。
加入依赖
在 pom.xml 加入 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-mongodb/artifactId/dependency配置连接参数
在系统配置文件中配置
spring:data:mongodb:uri: mongodb://wuwii:123456localhost:27017/learn测试使用
创建实体
Data
Document(collection pet) // 标识要持久化到MongoDB的域对象。模型名是 pet
public class Pet implements Serializable {Id//Indexed(unique true) // 使用MongoDB的索引特性标记一个字段private Long id;Field(pet_name) //自定义设置对应MongoDB中的keyprivate String name;private String species;
}创建 dao 接口完成基础操作
Repository
public class PetDaoImpl implements PetDao {Autowiredprivate MongoTemplate mongoTemplate;Overridepublic Pet find(Long id) {return mongoTemplate.findById(id, Pet.class);}Overridepublic ListPet findAll() {return mongoTemplate.findAll(Pet.class);}Overridepublic void add(Pet pet) {mongoTemplate.insert(pet);}Overridepublic void update(Pet pet) {Query query new Query();Criteria criteria new Criteria(id);criteria.is(pet.getId());query.addCriteria(criteria);Update update new Update();update.set(pet_name, pet.getName()).set(species, pet.getSpecies());mongoTemplate.updateFirst(query, update, Pet.class); // 条件更新的数据更新的类型}Overridepublic void delete(Long id) {Criteria criteria new Criteria(id);criteria.is(id);Query query new Query();query.addCriteria(criteria);mongoTemplate.remove(query, Pet.class); // 删除的条件、删除的类型}
}简单测试下
SpringBootTest
RunWith(SpringRunner.class)
FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PetDaoTest {Autowiredprivate PetDao petDao;private Pet pet;Beforepublic void before() {pet new Pet();pet.setId(1L);pet.setName(Tom);pet.setSpecies(cat);}Afterpublic void after() {}Testpublic void test01Add() {Pet pet new Pet();pet.setId(1L);pet.setName(Tom);pet.setSpecies(cat);petDao.add(pet);}Testpublic void test02Find() {Assert.assertThat(pet, Matchers.equalTo(petDao.find(pet.getId())));}Testpublic void test03FindAll() {System.out.println(petDao.findAll());}Testpublic void test04Update() {pet.setName(KronChan);petDao.update(pet);Assert.assertThat(pet, Matchers.equalTo(petDao.find(pet.getId())));}Testpublic void test05Delete() {petDao.delete(pet.getId());Assert.assertThat(null, Matchers.equalTo(petDao.find(pet.getId())));}}去数据库验证结果 use learn
switched to db learndb.pet.find()
{ _id : NumberLong(1), _class : com.wuwii.testmongodb.Pet, pet_name : KronChan, species : cat }多数据源的使用
未完成