Spring 4 + MongoDB + Gradle Integration Annotation Example

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介:

In this page we will learn Spring 4 and MongoDB which is a NoSQL database. MongoDB stores data in BSON format which is Binary JSON. MongoDB is easy to use and perform faster. Spring provides different classes to work with MongoDB . MongoRepository is used to define our repository class in which we define different methods to retrieve data. In configuration class, we have MongoDbFactory and MongoTemplate. MongoDbFactory provides database instance and MongoTemplate provides different methods for MongoDB database transaction. In this example, we will save some employee and apply our repository methods to retrieve data from MongoDB. 

Software Required to Run Example

To run the example we need the following software. 
1. JDK 6 
2. Gradle 
3. Eclipse 
4. MongoDB 

Install MongoDB Server

Find the steps to install MongoDB server. 
1. To install MongoDB Server, visit the URL  Install MongoDB and if looking for windows, visit the URL  Install MongoDB on Windows 
2. Download Binary file and install. 
3. Create \data\db directory in MongoDB home. 
4. To run the server, go to bin directory using command prompt and run mongod file using the command mongod.exe --dbpath C:\MongoDB-2.6\data\db 

Project Structure in Eclipse

Find the project structure of or demo in eclipse.

Spring 4 + MongoDB  + Gradle  Integration Annotation Example

Gradle for Spring data and MongoDB Boot

Find the build.gradle file that will use spring-boot-starter-data-mongodb. 
build.gradle

apply plugin: 'java'apply plugin: 'eclipse'archivesBaseName = 'Concretepage'version = '1.0-SNAPSHOT' repositories {
    maven { url "https://repo.spring.io/libs-release" }
    mavenLocal()
    mavenCentral()}dependencies {
 	compile 'org.springframework.boot:spring-boot-starter-data-mongodb:1.2.0.RELEASE'
 	compile 'org.springframework.boot:spring-boot-starter-security:1.2.0.RELEASE'}

Create an Entity Class

Find the entity class for the demo. Using @Id annotation we create an identifier for our entity. 
Employee.java

package com.concretepage.mongodb.entity;import org.springframework.data.annotation.Id;public class Employee { 
	@Id
	public Integer id;
	public String name;
        public Integer age;
	public Employee(Integer id, String name, Integer age){
		this.id = id;
		this.name=name;
		this.age=age;
	}}

Create Repository Class using MongoRepository

Spring data provides MongoRepository using which we create our repository class to add required methods which retrieves data. Queries are written in BSON syntax. ?0 is used to get parameter value. If we want to filter property, we can use value and fields keys. Value is which we will pass as input and fields are those properties which will be populated. 
EmployeeRepository.java

package com.concretepage.mongodb;import java.util.List;import org.springframework.data.mongodb.repository.MongoRepository;import org.springframework.data.mongodb.repository.Query;import org.springframework.stereotype.Component;import com.concretepage.mongodb.entity.Employee;@Componentpublic interface EmployeeRepository extends MongoRepository<Employee, String> {
    @Query("{ 'name' : ?0 }")
    Employee getEmployeeByName(String name);
    
    @Query(value="{ 'age' : ?0}", fields="{ 'name' : 1, 'id' : 1}")
    List getEmployeeByAge(int age);}

Configuration Class: MongoDbFactory and MongoTemplate 

Create a configuration class to declare MongoDbFactory , MongoTemplate and our repository class i.e EmployeeRepository. 
MongoDbFactory: Create database instances. In our example, we are creating a database with the name concretepage
MongoClient: Using IP and port of MongoDB server, MongoClient create an instance for the client. 
UserCredentials: Provides the instance to set username and password of MongoDB server. By default both are blank. 
SimpleMongoDbFactory: Provides MongoDB instance using MongoClient, database name and UserCredentials. 
MongoTemplate: It has basic sets of operation for MongoDB. 
Find the configuration class. 
MongoDBConfig.java

package com.concretepage.mongodb.config;  import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.data.authentication.UserCredentials;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.repository.config.EnableMongoRepositories;import com.concretepage.mongodb.EmployeeRepository;import com.mongodb.MongoClient;@Configuration@EnableMongoRepositories(basePackages="com.concretepage.mongodb" )public class MongoDBConfig {
    @Autowired
    EmployeeRepository employeeRepository;  
    @Bean
    public  MongoDbFactory mongoDbFactory() throws Exception {
    	MongoClient mongoClient = new MongoClient("localhost",27017);
    	UserCredentials userCredentials = new UserCredentials("","");
        return new SimpleMongoDbFactory(mongoClient, "concretepage",userCredentials);
    }
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
        return mongoTemplate;
    }}

Main Class: Save Data and Fetch using Repository Instance 

We will save some employee in MongoDB and then retrieve data using our repository method. 
Main.java

 package com.concretepage.mongodb;import java.util.List;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import com.concretepage.mongodb.config.MongoDBConfig;import com.concretepage.mongodb.entity.Employee;public class Main {
	public static void main(String[] args) {
	   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	   ctx.register(MongoDBConfig.class);
	   ctx.refresh();
	   EmployeeRepository employeeRepository = ctx.getBean(EmployeeRepository.class);
	   Employee ram = new Employee(1,"Ram",20);
	   Employee shyam = new Employee(2,"Shyam",19);
	   Employee mohan = new Employee(3,"Mohan",20);
	   Employee krishn = new Employee(4,"Krishn",20);
    	   //Delete if exists already
    	   employeeRepository.deleteAll();
    	   //Save employee
    	   employeeRepository.save(ram);
    	   employeeRepository.save(shyam);
    	   employeeRepository.save(mohan);
    	   employeeRepository.save(krishn);
    	   //Get employee By Name
    	   Employee emp = employeeRepository.getEmployeeByName(shyam.name);
    	   System.out.println(emp.name);
    	   //Fetch all employee for the age
    	   List employees = employeeRepository.getEmployeeByAge(20);
    	   System.out.println("----employee for the age 20----");
    	   for (Employee employee : employees) {
		System.out.println("Id:"+employee.id+",Name:"+employee.name);
	   }
       }}

Find the Output

Shyam----employee for the age 20----Id:1,Name:RamId:3,Name:MohanId:4,Name:Krishn

To check output in MongoDB console, find the below steps. 
1. To check output in MongoDB, open command prompt and go to bin directory and run 
mongo.exe
2. In our example, we have taken database name as concretepage. To go in database use the command 
use concretepage 
3. To check the data of employee entity, run the query as 
db.employee.find()

Spring 4 + MongoDB  + Gradle  Integration Annotation Example

Enjoy Learning.

Download Source Code 

spring-4-mongodb-gradle-integration-annotation-example.zip










本文转自 h2appy  51CTO博客,原文链接:http://blog.51cto.com/h2appy/1827204,如需转载请自行联系原作者
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
4月前
|
Java API 网络架构
关于 Spring Integration 你知道多少,包含集成MQTT案例讲述及源码3
关于 Spring Integration 你知道多少,包含集成MQTT案例讲述及源码
161 0
关于 Spring Integration 你知道多少,包含集成MQTT案例讲述及源码3
|
4月前
|
NoSQL Java MongoDB
Spring Boot中MongoDB的使用和实战
Spring Boot中MongoDB的使用和实战
61 0
|
2月前
|
消息中间件 Java 网络架构
穿越消息之路:深入探讨Spring Integration的魅力
穿越消息之路:深入探讨Spring Integration的魅力
54 0
|
4月前
|
XML Java API
关于 Spring Integration 你知道多少,包含集成MQTT案例讲述及源码2
关于 Spring Integration 你知道多少,包含集成MQTT案例讲述及源码
144 0
|
4月前
|
消息中间件 Java Docker
关于 Spring Integration 你知道多少,包含集成MQTT案例讲述及源码1
关于 Spring Integration 你知道多少,包含集成MQTT案例讲述及源码
151 0
|
7月前
|
存储 NoSQL Java
MongoDB 入门教程系列之二:使用 Spring Boot 操作 MongoDB
MongoDB 入门教程系列之二:使用 Spring Boot 操作 MongoDB
98 0
|
7月前
|
缓存 NoSQL Java
Spring Session MongoDB管理会话
Spring Session MongoDB管理会话
60 0
BXA
|
11月前
|
消息中间件 监控 安全
Spring Integration整合不同系统-提升管理效率
企业需要将不同的信息系统人员及其工作流程进行统一管理和整合,以提高生产效率、降低成本,加强信息安全保障。Spring Integration作为一种集成框架,旨在简化企业信息流程化的实现。其解耦和整合的特性让程序员更加专注于业务开发需求,而不必担心不同数据源的集成问题
BXA
187 0
|
存储 缓存 NoSQL
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
快速学习 Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存
424 0
Spring Boot2.5 实战 MongoDB 与高并发 Redis 缓存|学习笔记
|
存储 NoSQL 安全
Spring Boot 2.0实战 MongoDB 数据库与面试题|学习笔记
快速学习 Spring Boot 2.0实战 MongoDB 数据库与面试题。
191 0
Spring Boot 2.0实战 MongoDB 数据库与面试题|学习笔记