MongoDB 1 是能夠應用於各類規模的企業、各個行業以及各種應用程序的開源數據庫。基於分佈式文件存儲的數據庫。由C++語言編寫。旨在爲WEB應用提供可擴展的高性能數據存儲解決方案。MongoDB是一個高性能,開源,無模式的文檔型數據庫,是當前NoSql數據庫中比較熱門的一種。css
Spring Boot 對 MongoDB 的數據源操做進行了封裝。java
在 pom.xml 加入:spring
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
在系統配置文件中配置:mongodb
spring:
data:
mongodb:
uri: mongodb://wuwii:123456@localhost: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中的key
private String name;
private String species;
}
@Repository
public class PetDaoImpl implements PetDao {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public Pet find(Long id) {
return mongoTemplate.findById(id, Pet.class);
}
@Override
public List<Pet> findAll() {
return mongoTemplate.findAll(Pet.class);
}
@Override
public void add(Pet pet) {
mongoTemplate.insert(pet);
}
@Override
public 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); // 條件,更新的數據,更新的類型
}
@Override
public 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 {
@Autowired
private PetDao petDao;
private Pet pet;
@Before
public void before() {
pet = new Pet();
pet.setId(1L);
pet.setName("Tom");
pet.setSpecies("cat");
}
@After
public void after() {
}
@Test
public void test01Add() {
Pet pet = new Pet();
pet.setId(1L);
pet.setName("Tom");
pet.setSpecies("cat");
petDao.add(pet);
}
@Test
public void test02Find() {
Assert.assertThat(pet, Matchers.equalTo(petDao.find(pet.getId())));
}
@Test
public void test03FindAll() {
System.out.println(petDao.findAll());
}
@Test
public void test04Update() {
pet.setName("KronChan");
petDao.update(pet);
Assert.assertThat(pet, Matchers.equalTo(petDao.find(pet.getId())));
}
@Test
public void test05Delete() {
petDao.delete(pet.getId());
Assert.assertThat(null, Matchers.equalTo(petDao.find(pet.getId())));
}
}
> use learn
switched to db learn
> db.pet.find()
{ "_id" : NumberLong(1), "_class" : "com.wuwii.testmongodb.Pet", "pet_name" : "KronChan", "species" : "cat" }
未完成數據庫