MongoDB application example


MongoDB application example


JDBC application example:
<dependency>
	<groupId>org.mongodb</groupId>
	<artifactId>mongodb-driver</artifactId>
	<version>3.2.2</version>
</dependency>


import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoDBJDBC {
	public static void main(String args[]) {
		try {
			// Connect to the MongoDB service if it is a remote connection, replace "localhost" with the IP address of the server
			// The two parameters of ServerAddress() are the server address and port respectively
			ServerAddress serverAddress = new ServerAddress("localhost", 27017);
			List<ServerAddress> addrs = new ArrayList<ServerAddress>();
			addrs.add(serverAddress);

			// The three parameters of MongoCredential.createScramSha1Credential() are username and database name and password respectively
			MongoCredential credential = MongoCredential.createScramSha1Credential("admin", "admin",
					"admin".toCharArray());
			List<MongoCredential> credentials = new ArrayList<MongoCredential>();
			credentials.add(credential);

			// Get MongoDB connection through connection authentication
			MongoClient mongoClient = new MongoClient(addrs, credentials);

			// connect to the database
			MongoDatabase mongoDatabase = mongoClient.getDatabase("testDB"); // get the database to operate

			MongoCollection<Document> collection = mongoDatabase.getCollection("test");// Get the collection to operate
			if (collection == null) {
				mongoDatabase.createCollection("test");// Collection creation
				System.out.println("Collection created successfully");
				System.out.println("Connect to database successfully");
			}

			collection = mongoDatabase.getCollection("test");// Get the collection to operate
			System.out.println("Collection test selection succeeded");
			// insert document
			/**
			 * 1. Create document org.bson.Document parameter is key-value format 2. Create document collection List
			 * <Document> 3. Insert the document collection into the database collection mongoCollection.insertMany(List
			 * <Document>) Inserting a single document can use mongoCollection.insertOne(Document)
			 */
			Document document = new Document("title", "MongoDB").append("description", "database").append("likes", 100)
					.append("by", "Fly"); // create a new document set
			List<Document> documents = new ArrayList<Document>();
			documents.add(document);
			collection.insertMany(documents);// Insert the document set into the collection

			System.out.println("Document inserted successfully");

			// retrieve all documents
			/**
			 * 1. Get the iterator FindIterable<Document> 2. Get the cursor MongoCursor<Document> 3.
			 * Traverse the retrieved document collection through the cursor
			 */
			FindIterable<Document> findIterable = collection.find(); // find all document collections
			MongoCursor<Document> mongoCursor = findIterable.iterator();
			while (mongoCursor.hasNext()) {
				System.out.println(mongoCursor.next());
			}

			mongoClient.close(); // close the connection
		} catch (Exception e) {
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
		}
	}
}


Refer to the original text (JDBC application): http://www.runoob.com/mongodb/mongodb-java.html


spring data mongodb(MongoTemplate)

<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-mongodb</artifactId>
	<version>1.9.3.RELEASE</version>
</dependency>


applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
        xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
            http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd">

 <context:annotation-config />
	<!-- <task:annotation-driven /> -->
	<context:component-scan base-package="com" />

    <mongo:mongo host="localhost" port="27017" >
            <!-- If the optional option is not configured, the value is the default -->
          <mongo:options
              connections-per-host="8"
              threads-allowed-to-block-for-connection-multiplier="4"
              connect-timeout="1000"
              max-wait-time="1500"
              auto-connect-retry="true"
              socket-keep-alive="true"
              socket-timeout="1500"
              slave-ok="true"
              write-number="1"
              write-timeout="0"
              write-fsync="true"
                  />
    </mongo:mongo>

    <mongo:db-factory id="anotherMongoDbFactory"
    host="localhost"
    port="27017"
    dbname="admin"
    username="admin"
    password="admin" mongo-ref="mongo"/>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="anotherMongoDbFactory" />
       <!--  <constructor-arg ref="mongo" />
        <constructor-arg name="databaseName" value="test" />The name of the linked database -->
    </bean>
     <bean id="natureRepository"
        class="com.NatureRepositoryImpl">
    </bean>
</beans>



package com;

public class Address {
	private String addr;
private String pro;

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	public String getPro() {
		return pro;
	}

	public void setPro(String pro) {
		this.pro = pro;
	}
}



package com;

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

@Document
public class Person {
	@Id
	private String id;
	private String name;
	private int age;

	private Address address;

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
	}

}



package com;

import java.util.List;

import com.mongodb.WriteResult;

public interface Repository<T> {

	public List<T> getAllObjects();

	public void saveObject(T object);

	public T getObject(String id);

	public WriteResult updateObject(String id, String name);

	public void deleteObject(String id);

	public void createCollection();

	public void dropCollection();
}


package com;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.mongodb.WriteResult;

public class NatureRepositoryImpl implements Repository<Person> {
	@Resource
	MongoTemplate mongoTemplate;

	public List<Person> getAllObjects() {
		return mongoTemplate.findAll(Person.class);
	}

	public void saveObject(Person tree) {
		mongoTemplate.insert(tree);
	}

	public Person getObject(String id) {
		// return mongoTemplate.find(new Query(Criteria.where("id").is(id)),
		// Person.class).get(0);
		return mongoTemplate.findById(id, Person.class);
	}

	public WriteResult updateObject(String id, String name) {
		return mongoTemplate.updateFirst(new Query(Criteria.where("id").is(id)), Update.update("name", name),
				Person.class);
	}

	public void deleteObject(String id) {
		mongoTemplate.remove(new Query(Criteria.where("id").is(id)), Person.class);
	}

	public void createCollection() {
		if (!mongoTemplate.collectionExists(Person.class)) {
			mongoTemplate.createCollection(Person.class);
		}
	}

	public void dropCollection() {
		if (mongoTemplate.collectionExists(Person.class)) {
			mongoTemplate.dropCollection(Person.class);
		}
	}
}



package com;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MongoTest {
	public static void main(String[] args) throws InterruptedException {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");

		Repository<Person> repository = applicationContext.getBean(NatureRepositoryImpl.class);
		System.out.println(repository);

		repository.dropCollection();
		repository.createCollection();
		Person person = new Person();
		Address address = new Address();

		address.setAddr("Hefei");
		address.setPro("Anhui");
		person.setAddress(address);
		person.setAge(20);
		person.setName("senssic");
		person.setId("1");
		repository.saveObject(person);

		System.out.println("1. " + repository.getAllObjects().toString());
		person.setId("101");
		repository.saveObject(person);
		System.out.println("2. " + repository.getAllObjects().toString());

		person = repository.getObject("1");
		System.out.println(person.toString());

		System.out.println("Hefei");
		repository.updateObject("1", "sen");
		System.out.println("3. " + repository.getAllObjects().toString());
		repository.deleteObject("1");
		System.out.println("4. " + repository.getAllObjects().toString());
	}
}


Reference text (configuration parameters): http://blog.csdn.net/freebird_lb/article/details/8229567
Reference text (configuration parameters): http://www.cnblogs.com/basecn/p/springmongo_intergration_cfg.html
Reference text : http://www.xuebuyuan.com/2207064.html
Reference text (Query (query statement)): http://www.07net01.com/2015/08/889188.html
Reference text: http://docs. spring.io/spring-data/mongodb/docs/current/reference/html/Reference
original text: http://blog.csdn.net/zhongweijian/article/details/7625286

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326943612&siteId=291194637