初识MongoDB
非关系型数据库,数据无固定的模式,nosql,键值对的存取方式,分布式计算,可扩展性高。
首先需要搭建本地的mongodbService。数据存储在data文件夹中。
配置环境变量后,mongo -version,查看版本。或者进入bin目录,操作数据库。
我的学习新东西的方式,就是先做一个小demo,然后进而研究其原理。
目前学习了两种方式,第一种,Repository类,实现MongoRepository接口。第二种,使用MongoTemplate类。
以上两种方式,实际上是对底层数据的增删改查操作,进行了封装,我们只需要调用其接口即可。
实现MongoRepository,pom.xml如何MongoDB的相关依赖。

@SpringBootApplication public class MongoApplication { //springboot项目的入口 public static void main(String[] args) { SpringApplication.run(MongoApplication.class, args); } }

package com.cn.mongo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.cn.mongo.model.User; import com.cn.mongo.repository.UserRepository2; import com.cn.mongo.service.UserService; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public String saveUser() { User user = new User(); user.setId(11l); user.setUserName("Tom"); user.setPassWord("imissyou"); return userService.saveUser(user) ? "添加成功" : "添加失败"; } @GetMapping("/findUser") public String getUser() { return userService.getUserByName(11l) ? "存在此人" : "查无此人"; } @GetMapping("/deleteUser") public String deleteUserById() { return userService.deleteUserById(11l) ? "删除失败" : "删除成功"; } @GetMapping("/getPage") public String getPage() { return userService.getPage().getContent().toString(); } }

package com.cn.mongo.model; public class User { private Long id; private String userName; private String passWord; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } @Override public String toString() { return "User{" + "id=" + id + ", userName='" + userName + '\'' + ", passWord='" + passWord + '\'' + '}'; } }

package com.cn.mongo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import com.cn.mongo.model.User; import com.cn.mongo.repository.UserRepository; import com.cn.mongo.repository.UserRepository2; @Service public class UserService { @Autowired private UserRepository userRepository; public boolean getUserByName(Long id) { return userRepository.existsById(id); } public boolean saveUser(User user) { userRepository.save(user); return userRepository.existsById(user.getId()); } public boolean deleteUserById(Long id) { userRepository.deleteById(id); return userRepository.existsById(id); } public Page getPage() { //Sort sort = new Sort(Sort.Direction.DESC,"id"); Pageable pageable = PageRequest.of(0,2); return userRepository.findAll(pageable); } }

package com.cn.mongo.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; import com.cn.mongo.model.User; public interface UserRepository extends MongoRepository<User, Long> { User findByUserName(String userName); Page<User> findAll(Pageable var1); }

spring.application.name=spring-boot-mongodb-repository spring.data.mongodb.uri=mongodb://localhost:27017/test server.port=8009

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>springboot-class-5</groupId> <artifactId>springboot-class-5</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springboot-class-5 Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencies> <!-- Compile --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
MongoTemplate类方式,与上面代码相似的全部沈略。MongoConfig使用了注解:@Configuration,对配置文件进行扫描,通过uri,以及对数据库test进行指定,完成环境的准备。

package com.cn.mongo.repository; import com.cn.mongo.model.User; public interface UserRepository2 { public void saveUser(User user); public User findUserByUserName(String userName); public long updateUser(User user); public void deleteUserById(Long id); }

package com.cn.mongo.repository.impl; 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.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; import com.cn.mongo.model.User; import com.cn.mongo.repository.UserRepository2; import com.mongodb.client.result.UpdateResult; @Component public class UseerRepositoryImpl implements UserRepository2 { @Autowired private MongoTemplate mongoTemplate; public void saveUser(User user) { mongoTemplate.save(user); } public User findUserByUserName(String userName) { Query query = new Query(Criteria.where("userName").is(userName)); return mongoTemplate.findOne(query, User.class); } public long updateUser(User user) { Query query = new Query(Criteria.where("id").is(user.getId())); Update update = new Update().set("userName", user.getUserName()).set("password", user.getPassWord()); UpdateResult updateResult = mongoTemplate.updateFirst(query, update, User.class); if (updateResult != null) { return updateResult.getMatchedCount(); } return 0; } public void deleteUserById(Long id) { Query query = new Query(Criteria.where("id").is(id)); mongoTemplate.remove(query, User.class); } }

package com.cn.mongo.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; @Configuration public class MongoConfig { @Value("${mongodb.uri2}") private String mongoUri; @Primary @Bean(name = "mongoTemplate") public MongoTemplate mongoTemplate() { MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoDbFactory()), new MongoMappingContext()); converter.setTypeMapper(new DefaultMongoTypeMapper(null)); return new MongoTemplate(mongoDbFactory(), converter); } @Bean @Primary public MongoDbFactory mongoDbFactory() { MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoUri)); return new SimpleMongoDbFactory(mongoClient, "test"); } }

spring.application.name=spring-boot-mongodb-template mongodb.uri=mongodb://localhost:27017 spring.http.encoding.force-response=true
以上是单个数据库,如果是多个数据库,应该如何操作。

package com.cn.mogo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.cn.mogo.model.User; import com.cn.mogo.service.UserService; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/saveUser") public String saveUser() { User user = new User(); user.setId("00111"); user.setUserName("Harving"); user.setPassWord("1231123"); return userService.saveUser(user); } @GetMapping("/findUser") public String findUser(String id) { return userService.findUser(id).toString(); } }

package com.cn.mogo.service; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cn.mogo.model.User; import com.cn.mogo.repository.primary.PrimaryRepository; import com.cn.mogo.repository.secondary.SecondaryRepository; @Service public class UserService { @Autowired PrimaryRepository primaryRepository; @Autowired SecondaryRepository secondaryRepository; public String saveUser(User user) { primaryRepository.save(user); secondaryRepository.save(user); String result = primaryRepository.existsById(user.getId())?"primary:存在":"不存在"; result+= secondaryRepository.existsById(user.getId())?"secondary:存在":"不存在"; return result; } public User findUser(String id) { Optional<User> userOptional = primaryRepository.findById(id); return userOptional.get(); } }

package com.cn.mogo.repository.primary; import org.springframework.data.mongodb.repository.MongoRepository; import com.cn.mogo.model.User; public interface PrimaryRepository extends MongoRepository<User, String> { }

package com.cn.mogo.repository.secondary; import com.cn.mogo.model.User; import org.springframework.data.mongodb.repository.MongoRepository; public interface SecondaryRepository extends MongoRepository<User,String>{ }

package com.cn.mogo.config; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.cn.mogo.config.prop.MultipleMongoProperties; @Configuration @EnableConfigurationProperties(MultipleMongoProperties.class) @EnableMongoRepositories(basePackages = "com.cn.mogo.repository.primary",mongoTemplateRef = "primaryMongoTemplate") public class PrimaryMongoConfig { }

package com.cn.mogo.config; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import com.cn.mogo.config.prop.MultipleMongoProperties; @Configuration @EnableConfigurationProperties(MultipleMongoProperties.class) @EnableMongoRepositories(basePackages = "com.cn.mogo.repository.secondary", mongoTemplateRef = "secondaryMongoTemplate") public class SecondaryMongoConfig { }

package com.cn.mogo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.mongo.MongoProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import com.cn.mogo.config.prop.MultipleMongoProperties; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; @Configuration public class MultipleMongoConfig { @Autowired private MultipleMongoProperties mongoProperties; @Primary @Bean(name = "primaryMongoTemplate") public MongoTemplate primaryMongoTemplate() throws Exception { MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoProperties.getPrimary().getUri())); return new MongoTemplate(new SimpleMongoDbFactory(mongoClient,mongoProperties.getPrimary().getDatabase())); } @Bean @Qualifier( "secondaryMongoTemplate") public MongoTemplate secondaryMongoTemplate() throws Exception { MongoClient mongoClient = new MongoClient(new MongoClientURI(mongoProperties.getSecondary().getUri())); return new MongoTemplate(new SimpleMongoDbFactory(mongoClient,mongoProperties.getSecondary().getDatabase())); } }

package com.cn.mogo.config.prop; import org.springframework.boot.autoconfigure.mongo.MongoProperties; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "mongodb") public class MultipleMongoProperties { private MongoProperties primary = new MongoProperties(); private MongoProperties secondary = new MongoProperties(); public MongoProperties getPrimary() { return primary; } public void setPrimaty(MongoProperties primary) { this.primary = primary; } public MongoProperties getSecondary() { return secondary; } public void setSecondary(MongoProperties secondary) { this.secondary = secondary; } }
spring.application.name=spring-boot-multi-mongodb mongodb.primary.uri=mongodb://localhost:27017 mongodb.primary.database=primary mongodb.secondary.uri=mongodb://localhost:27017 mongodb.secondary.database=secondary server.port=9090
接下来,学习mongodb的基本命令,对数据库,集合,文档的增删改查操作。
我们不一样