jarod8016b 发表于 2018-10-25 13:06:21

Spring 4 + MongoDB + Gradle Integration Annotation Example-GONE WITH THE WIND-51

  http://www.concretepage.com/spring-4/spring-4-mongodb-gradle-integration-annotation-example

  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>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 URLInstall MongoDB and if looking for windows, visit the URLInstall 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.

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>
  Find the 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>
  Spring data provides MongoRepository using which we create our repository>  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>
  Create a configuration>  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>  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
  
    publicMongoDbFactory 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>  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()

  Enjoy Learning.
Download Source Code
  spring-4-mongodb-gradle-integration-annotation-example.zip


页: [1]
查看完整版本: Spring 4 + MongoDB + Gradle Integration Annotation Example-GONE WITH THE WIND-51