- 深入實踐Spring Boot
- 陳韶健
- 1246字
- 2019-01-04 03:26:53
2.3 使用MongoDB
在當前流行的NoSQL數據庫中,MongoDB是大家接觸比較早而且用得比較多的數據庫。MongoDB是文檔型的NoSQL數據庫,具有大數據量、高并發等優勢,但缺點是不能建立實體關系,而且也沒有事務管理機制。
2.3.1 MongoDB依賴配置
在Spring Boot中使用MongoDB也像使用JPA一樣容易,并且同樣擁有功能完善的資源庫。同樣的,要使用MongoDB,首先必須在工程的Maven中引入它的依賴,如代碼清單2-14所示。除了MongoDB本身的依賴之外,還需要一些附加的工具配套使用。
代碼清單2-14 使用MongoDB的Maven依賴配置
<dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.pegdown</groupId> <artifactId>pegdown</artifactId> <version>1.4.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-hateoas</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> </dependency> </dependencies>
2.3.2 文檔建模
MongoDB是文檔型數據庫,使用MongoDB也可以像使用關系型數據庫那樣為文檔建模。如代碼清單2-15所示,為用戶文檔建模,它具有用戶名、密碼、用戶名稱、郵箱和注冊日期等字段,有一個用來保存用戶角色的數據集,還定義了一個構造函數,可以很方便地用來創建一個用戶實例。
代碼清單2-15 用戶文檔建模
@Document(collection = "user") public class User { @Id private String userId; @NotNull @Indexed(unique = true) private String username; @NotNull private String password; @NotNull private String name; @NotNull private String email; @NotNull private Date registrationDate = new Date(); private Set<String> roles = new HashSet<>(); public User() { } @PersistenceConstructor public User(String userId, String username, String password, String name, String email, Date registrationDate, Set<String> roles) { this.userId = userId; this.username = username; this.password = password; this.name = name; this.email = email; this.registrationDate = registrationDate; this.roles = roles; }……
2.3.3 文檔持久化
MongoDB也有像使用JPA那樣的資源庫,如代碼清單2-16所示,為用戶文檔創建了一個Repository接口,繼承于MongoRepository,實現了文檔持久化。
代碼清單2-16 用戶文檔持久化
public interface UserRepository extends MongoRepository<User, String> { User findByUsername(String username); }
MongoRepository的繼承關系如圖2-4所示,看起來跟JPA的資源庫的繼承關系沒有什么兩樣,它也包含訪問數據庫的豐富功能。

圖2-4 MongoRepository接口繼承關系
代碼清單2-17是用在測試中的使用MongoDB的一個配置類定義,其中@PropertySource指定讀取數據庫配置文件的位置和名稱,@EnableMongoRepositories啟用資源庫并設定定義資源庫接口放置的位置,這里使用環境變量Environment來讀取配置文件的一些數據庫配置參數,然后使用一個數據庫客戶端,連接MongoDB服務器。
代碼清單2-17 TestDataSourceConfig配置類
@Configuration @EnableMongoRepositories(basePackages = "dbdemo.mongo.repositories") @PropertySource("classpath:test.properties") public class TestDataSourceConfig extends AbstractMongoConfiguration { @Autowired private Environment env; @Override public String getDatabaseName(){ return env.getRequiredProperty("mongo.name"); } @Override @Bean public Mongo mongo() throws Exception { ServerAddress serverAddress = new ServerAddress(env.getRequiredProperty ("mongo.host")); List<MongoCredential> credentials = new ArrayList<>(); return new MongoClient(serverAddress, credentials); } }
2.3.4 MongoDB測試
如果還沒有安裝MongoDB服務器,可以參照附錄B的方法安裝并啟動一個MongoDB服務器。然后,使用如代碼清單2-18所示的配置方法配置連接服務器的一些參數,該配置假定你的MongoDB服務器安裝在本地,并使用默認的數據庫端口:27017。
代碼清單2-18 MongoDB數據庫配置
# MongoDB mongo.host=localhost mongo.name=test mongo.port=27017
這樣就可以編寫一個JUint測試例子來測試UserRepository接口的使用情況,如代碼清單2-19所示。測試例子首先使用用戶文檔類創建一個用戶對象實例,然后使用資源庫接口調用save方法將用戶對象保存到數據庫中,最后使用findAll方法查詢所有用戶的列表,并使用一個循環輸出用戶的簡要信息。
代碼清單2-19 MongoDB測試
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {TestDataSourceConfig.class}) @FixMethodOrder public class RepositoryTests { private static Logger logger = LoggerFactory.getLogger(RepositoryTests.class); @SuppressWarnings("SpringJavaAutowiringInspection") @Autowired UserRepository userRepository; @Before public void setup(){ Set<String> roles = new HashSet<>(); roles.add("manage"); User user = new User("1","user","12345678","name","email@com.cn",new Date(), roles); userRepository.save(user); } @Test public void findAll(){ List<User> users = userRepository.findAll(); Assert.notNull(users); for(User user : users){ logger.info("===user=== userid:{}, username:{}, pass:{}, registra tionDate:{}", user.getUserId(), user.getName(), user.getPassword(), user. getRegistrationDate()); } } }
現在可以在IDEA的Run/Debug Configuration配置中增加一個JUint測試項目,模塊選擇mongodb,工作目錄選擇模塊所在的工程根目錄,類選擇上面編寫的測試例子,即dbdemo.mongo.test.RepositoryTests,并將配置保存為mongotest。
使用Debug方式運行測試項目mongotest。如果通過測試,將輸出查到的用戶的簡要信息,如下所示:
dbdemo.mongo.test.RepositoryTests - ===user=== userid:1, username:name, pass:12345678, registrationDate:Tue Jun 07 14:26:02 CST 2016
這時使用MongoDB數據庫客戶端輸入下面的查詢指令,也可以查到這條文檔的詳細信息,這是一條JSON結構的文本信息。
> db.user.find() { "_id" : "1", "_class" : "dbdemo.mongo.models.User", "username" : "user", "password" : "12345678", "name" : "name", "email" : "email@com.cn", "registrationDate" : ISODate("2016-04-13T06:27:02.423Z"), "roles" : [ "manage" ] }
- Java高并發核心編程(卷2):多線程、鎖、JMM、JUC、高并發設計模式
- Java EE框架整合開發入門到實戰:Spring+Spring MVC+MyBatis(微課版)
- 數據結構與算法JavaScript描述
- 軟件架構:Python語言實現
- Linux操作系統基礎案例教程
- Java程序設計
- Learning Unreal Engine Android Game Development
- Node.js 12實戰
- Mastering ASP.NET Core 2.0
- Java程序設計實用教程(第2版)
- Keil Cx51 V7.0單片機高級語言編程與μVision2應用實踐
- 讀故事學編程:Python王國歷險記
- Socket.IO Cookbook
- 川哥教你Spring Boot 2實戰
- 生成藝術:Processing視覺創意入門