MongoDB应用例子
MongoDB应用例子
JDBC应用例子:
<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 { // 连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址 // ServerAddress()两个参数分别为 服务器地址 和 端口 ServerAddress serverAddress = new ServerAddress("localhost", 27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); // MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码 MongoCredential credential = MongoCredential.createScramSha1Credential("admin", "admin", "admin".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); // 通过连接认证获取MongoDB连接 MongoClient mongoClient = new MongoClient(addrs, credentials); // 连接到数据库 MongoDatabase mongoDatabase = mongoClient.getDatabase("testDB"); // 得到要操作的数据库 MongoCollection<Document> collection = mongoDatabase.getCollection("test");// 得到要操作的集合 if (collection == null) { mongoDatabase.createCollection("test");// 集合创建 System.out.println("集合创建成功"); System.out.println("Connect to database successfully"); } collection = mongoDatabase.getCollection("test");// 得到要操作的集合 System.out.println("集合 test 选择成功"); // 插入文档 /** * 1. 创建文档 org.bson.Document 参数为key-value的格式 2. 创建文档集合List * <Document> 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List * <Document>) 插入单个文档可以用 mongoCollection.insertOne(Document) */ Document document = new Document("title", "MongoDB").append("description", "database").append("likes", 100) .append("by", "Fly"); // 新建文档集 List<Document> documents = new ArrayList<Document>(); documents.add(document); collection.insertMany(documents);// 向集合插入文档集 System.out.println("文档插入成功"); // 检索所有文档 /** * 1. 获取迭代器FindIterable<Document> 2. 获取游标MongoCursor<Document> 3. * 通过游标遍历检索出的文档集合 */ FindIterable<Document> findIterable = collection.find(); // 查找所有文档集合 MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } mongoClient.close(); // 关闭连接 } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } } }
参考原文(JDBC应用):http://www.runoob.com/mongodb/mongodb-java.html
springdatamongodb(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" > <!-- 可选项如果不配置则为值为默认 --> <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" />链接数据库的名字 --> </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("合肥"); address.setPro("安徽"); 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("合肥"); repository.updateObject("1", "sen"); System.out.println("3. " + repository.getAllObjects().toString()); repository.deleteObject("1"); System.out.println("4. " + repository.getAllObjects().toString()); } }
参考原文(配置参数):http://blog.csdn.net/freebird_lb/article/details/8229567
参考原文(配置参数):http://www.cnblogs.com/basecn/p/springmongo_intergration_cfg.html
参考原文:http://www.xuebuyuan.com/2207064.html
参考原文(Query(查询语句)):http://www.07net01.com/2015/08/889188.html
参考原文:http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/
参考原文:http://blog.csdn.net/zhongweijian/article/details/7625286
相关推荐
lbyd0 2020-11-17
BigYellow 2020-11-16
sushuanglei 2020-11-12
我心似明月 2020-11-09
zhushenghan 2020-11-09
sunnnyduan 2020-10-16
不要皱眉 2020-10-14
xiaohai 2020-09-29
songxiugongwang 2020-09-22
萌亖 2020-09-17
LuckyLXG 2020-09-08
sdmzhu 2020-09-01
mkhhxxttxs 2020-09-16
xiaohai 2020-09-16
newcome 2020-09-09
jaylong 2020-08-19
大秦铁骑 2020-08-19
thatway 2020-08-19