Persisting document data using Spring Data MongoDB

introduce

  • NoSQL:not only SQL, non-relational data

  • MongoDB is documentary data, documents are independent entities, and document databases are not suitable for data with clear associations

Spring Data MongoDB

  • Spring Data MongoDB provides three ways to use MongoDB in Spring applications

    • Object-Document Mapping via Annotations

    • Template-based database access using MongoTemplate

    • Automated Runtime Repository Generation

import java.util.Collection;
import java.util.LinkedHashSet;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * Spring Data MongoDB Annotations map Java types to documents
 */
@Document        //This is a document
public class Order {

    @Id        //Specify id
    private String id;
    
    @Field("client")        //Override Default Domain Name
    private String customer;
    
    private String type;
    
    private Collection<Item> items = new LinkedHashSet<>();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCustomer() {
        return customer;
    }

    public void setCustomer(String customer) {
        this.customer = customer;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Collection<Item> getItems() {
        return items;
    }

    public void setItems(Collection<Item> items) {
        this.items = items;
    }
    
    
    
}
  • Enable MongoDB

    • Enable automatic JPA Repository generation for Spring Data via the @EnableJpaRepositories annotation

    • @EnableMongoRepositories implements the same functionality for MongoDB

    • First way:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.MongoClient;

/**
 * 
 * Spring Data MongoDB Configuration
 *
 */
@Configuration
@EnableMongoRepositories(basePackages="com.adagio.db")    //Enable Repository functionality for MongoDB
public class MongoConfig {

    /**
     * MongoTemplate Bean
     * @param mongoDbFactory
     * @return
     */
    @Bean
    public MongoOperations mongoTemplate(){
        return new MongoTemplate(mongoDbFactory());
    }
    
    /**
     * MongoDbFactory bean
     * @return
     */
    public MongoDbFactory mongoDbFactory(){
        return new SimpleMongoDbFactory(mongoClient(), "com.adagio.db");
    }
    
    /**
     * MongoClient bean
     * @return
     */
    public MongoClient mongoClient(){
        return new MongoClient("localhost");
    }
    
}
  • Second way

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * 
 * Spring Data MongoDB Configuration
 * Extend AbstractMongoConfiguration
 *
 */
@Configuration
@EnableMongoRepositories(basePackages="com.adagio.db")    //Enable Repository functionality for MongoDB
public class MongoConfig2 extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return "OrdersDB";        //Specify database name
    }

    @Autowired
    private Environment env;
    
    @Override
    public Mongo mongo() throws Exception {
//        return new MongoClient(); //Create Mongo Client
        
        //If the MongoDB server is running on another machine
//        return new MongoClient("mongoServer");
        
        //If the port MongoDB server is listening on is not the default port 27017
//        return new MongoClient("mongoServer", 37017);
        
        //If the MongoDB server is on a production configuration, authentication is enabled
        MongoCredential credential = MongoCredential.createCredential(
                env.getProperty("mongo.username") , "OrdersDB", 
                env.getProperty("mongo.password").toCharArray());
        return new MongoClient(
                new ServerAddress("localhost", 37017),
                Arrays.asList(credential));
    }

    
}
  • Annotate the model for MongoDB persistence

    • Spring Data MongoDB annotation for object-document mapping

      • The @Document flag maps to a realm object on a MongoDB document similar to the JPA @Entity annotation

      • @Id denotes a domain as an ID domain

      • @DbRef identifies other documents to be referenced by a field that may be in another database

      • @Field specifies custom metadata for the document field

      • @Version indicates that an attribute is used as a domain

    • Note: Attributes that are not annotated will also persist to the domain in the document unless transient is set

    • Note: The Order.items attribute, which is not an association relationship, is fully embedded in the Order

  • Accessing MongoDB using MongoTemplate

    • Configure the MonoTemplate bean configured in the class and inject it where it is used

    • @Autowired MongoOperations mongo;

    • MongoOperations is the interface implemented by MongoTemplate

    • void save(Object objectToSave, String collectionName);

    • The save first parameter is the newly created object, and the second parameter is the name of the document store to be saved

  • Write MongoDB Repository

    • Create Repository using Spring Data MongoDB

    • Enable Repository functionality for Spring Data MongoDB via the @EnableMongoRepositories annotation

    • Multiple CRUD operations can be inherited by extending the MongoRepository interface

  • Query method:

    • Custom Query

    • Specify Query

    • Mixed Definition Query

//Custom Query
    List<Order> findByCustomer(String customer);
    List<Order> getByCustomer(String customer);
    List<Order> readByCustomer(String customer);
    
    int countByCustomer(String customer);
    
    List<Order> findByCustomerLike(String customer);

    List<Order> findByCustomerAndType(String customer, String type);

    List<Order> getByType(String type);
        
    //Specify Query
    @Query("{customer:'Chuck Wagon'}")
    List<Order> findChucksOrders();

Mixed Custom Functions

  • First, define the intermediate interface

import java.util.List;

public interface OrderOperations {

    List<Order> findOrderByType(String t);
}
  • Writing hybrid implementations


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


public class OrderOperationsimpl implements OrderOperations {

    @Autowired
    private MongoOperations mongo;        //Inject MongoOperations
    @Override
    public List<Order> findOrderByType(String t) {
        String type = t.equals("NET") ? "WEB" : t;
        
        //Create Query
        Criteria where = Criteria.where("type").is(type);
        Query query = Query.query(where);
        
        //Execute Query
        return mongo.find(query, Order.class);
    }

}

Keywords: Java MongoDB Spring Database

Added by jokullsolberg on Fri, 07 Jun 2019 21:06:47 +0300