设为首页 收藏本站
查看: 1007|回复: 0

[经验分享] Spring 4 + MongoDB + Gradle Integration Annotation Example-GONE WITH THE WIND-51

[复制链接]

尚未签到

发表于 2018-10-25 13:06:21 | 显示全部楼层 |阅读模式
  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 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.
DSC0000.jpg

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
  
    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>  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()
DSC0001.jpg

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



运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-626383-1-1.html 上篇帖子: Mongodb七天总结—权限管理(2) 下篇帖子: 五个解决方案让MongoDB拥有RDBMS的鲁棒性事务
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表