博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 4 + MongoDB + Gradle Integration Annotation Example
阅读量:7236 次
发布时间:2019-06-29

本文共 7190 字,大约阅读时间需要 23 分钟。

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   and if looking for windows, visit the URL  
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
 {    @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 

本文转自 h2appy  51CTO博客,原文链接:http://blog.51cto.com/h2appy/1827204,如需转载请自行联系原作者
你可能感兴趣的文章
基于Solr的空间搜索
查看>>
给vmware的Linux虚拟机添加硬盘
查看>>
XMOVE3.0手持终端——软件介绍(三):在2KB内存的单片机上实现的的俄罗斯方块 (原创)...
查看>>
Kafka实战-Storm Cluster
查看>>
Spring中bean的范围
查看>>
JavaScript实现自适应窗口大小的网页
查看>>
跟我一起数据挖掘(5)——数据类型
查看>>
DIV 拖动效果高级篇
查看>>
SQL SERVER 2012链接到SQL SERVER 2000的问题解决案例
查看>>
Web性能--TCP的构成
查看>>
(十七)java冒泡排序和compareto
查看>>
linux内存查看方式
查看>>
Java魔法堂:String.format详解-
查看>>
线性重复动画
查看>>
炒冷饭系列:设计模式 建造者模式
查看>>
BAT解密:互联网技术发展之路(2)- 业务如何驱动技术发展
查看>>
bat脚本自动扫描制定文件夹下shp文件,并导入数据库,然后执行空间操作
查看>>
关于AsyncHttpClient的cz.msebera.android.httpclient.Header
查看>>
Codekit - 为Web前端打造的全能型神器(附推荐各种工具)
查看>>
JSP JSTL SQL标签操作数据库
查看>>