Spring 4 + MongoDB + Gradle Integration Annotation Example

本文涉及的产品
云数据库 MongoDB,独享型 2核8GB
推荐场景:
构建全方位客户视图
简介:

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,如需转载请自行联系原作者
目录
相关文章
|
26天前
|
监控 Cloud Native Java
Spring Integration 企业集成模式技术详解与实践指南
本文档全面介绍 Spring Integration 框架的核心概念、架构设计和实际应用。作为 Spring 生态系统中的企业集成解决方案,Spring Integration 基于著名的 Enterprise Integration Patterns(EIP)提供了轻量级的消息驱动架构。本文将深入探讨其消息通道、端点、过滤器、转换器等核心组件,以及如何构建可靠的企业集成解决方案。
89 0
|
消息中间件 监控 Java
Java一分钟之-Spring Integration:企业级集成
【6月更文挑战第11天】Spring Integration是Spring框架的一部分,用于简化企业应用的集成,基于EIP设计,采用消息传递连接不同服务。核心概念包括通道(Channel)、端点(Endpoint)和适配器(Adapter)。常见问题涉及过度设计、消息丢失与重复处理、性能瓶颈。解决策略包括遵循YAGNI原则、使用幂等性和事务管理、优化线程配置。通过添加依赖并创建简单消息处理链,可以开始使用Spring Integration。注意实践中要关注消息可靠性、系统性能,逐步探索高级特性以提升集成解决方案的质量和可维护性。
332 3
Java一分钟之-Spring Integration:企业级集成
|
NoSQL Java API
Spring Data MongoDB 使用
Spring Data MongoDB 使用
627 1
|
Java Spring
【Azure Service Bus】使用Spring Cloud integration示例代码,为多个 Service Bus的连接使用 ConnectionString 方式
【Azure Service Bus】使用Spring Cloud integration示例代码,为多个 Service Bus的连接使用 ConnectionString 方式
130 0
|
NoSQL Java MongoDB
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
【5月更文挑战第11天】本文介绍了如何将非关系型数据库MongoDB与Spring Boot框架集成,以实现高效灵活的数据管理。Spring Boot简化了Spring应用的构建和部署,MongoDB则以其对灵活数据结构的处理能力受到青睐。集成步骤包括:添加MongoDB依赖、配置连接信息、创建数据访问对象(DAO)以及进行数据操作。通过这种方式,开发者可以充分利用两者优势,应对各种数据需求。在实际应用中,结合微服务架构等技术,可以构建高性能、可扩展的系统。掌握MongoDB与Spring Boot集成对于提升开发效率和项目质量至关重要,未来有望在更多领域得到广泛应用。
367 3
【MongoDB 专栏】MongoDB 与 Spring Boot 的集成实践
|
NoSQL Java MongoDB
Spring Boot与MongoDB的集成应用
Spring Boot与MongoDB的集成应用
|
NoSQL Java MongoDB
Spring 5整合MongoDB
【5月更文挑战第9天】
138 2
|
存储 NoSQL Java
使用Spring Boot和MongoDB构建NoSQL应用
使用Spring Boot和MongoDB构建NoSQL应用
|
NoSQL Java MongoDB
如何在Spring Boot应用中集成MongoDB数据库
如何在Spring Boot应用中集成MongoDB数据库
|
NoSQL Java MongoDB
Spring Boot 整合 MongoDB 实战
本文介绍了如何使用Spring Boot整合MongoDB,实现数据持久化。步骤包括:环境准备(安装Java、MongoDB及创建Spring Boot项目)、在pom.xml中添加MongoDB依赖、配置MongoDB连接信息、创建映射MongoDB集合的实体类、定义MongoDB Repository接口、编写业务逻辑和服务层以及控制器层。通过测试确保整合成功。此实战教程帮助读者理解Spring Boot与MongoDB整合的基础,适用于快速构建Java应用。
1467 11

推荐镜像

更多