入门

本文介绍如何应用SpringDataMongoDB操作实体和数据库,本文只介绍最基本的例子,复杂的例子在后面的文章中介绍。

SpringDataMongoDB简介

SpringDataMongoDB是spring data的一个子项目,用来封装对MongoDB的操作,现在最新的版本是1.6.1。(截至2015年1月18日)

The Spring Data MongoDB project provides integration with the MongoDB document database. Key functional areas of Spring Data MongoDB are a POJO centric model for interacting with a MongoDB DBCollection and easily writing a Repository style data access layer.

MongoDB是一个非关系型数据库,这里不详细介绍了。

SpringDataMongoDB有以下一些特点:

  • Spring configuration support using Java based @Configuration classes or an XML namespace for a Mongo driver instance and replica sets.
  • MongoTemplate helper class that increases productivity performing common Mongo operations. Includes integrated object mapping between documents and POJOs.
  • Exception translation into Spring's portable Data Access Exception hierarchy
  • Feature Rich Object Mapping integrated with Spring's Conversion Service
  • Annotation based mapping metadata but extensible to support other metadata formats
  • Persistence and mapping lifecycle events
  • Low-level mapping using MongoReader/MongoWriter abstractions
  • Java based Query, Criteria, and Update DSLs
  • Automatic implementation of Repository interfaces including support for custom finder methods.
  • QueryDSL integration to support type-safe queries.
  • Cross-store persistance - support for JPA Entities with fields transparently persisted/retrieved using MongoDB
  • Log4j log appender
  • GeoSpatial integration
  • Map-Reduce integration
  • JMX administration and monitoring
  • CDI support for repositories
  • GridFS support

实体类定义

package com.chzhao.mongodbtest;

import org.springframework.data.annotation.Id;

public class Customer {
@Id
private String id; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getFirstName() {
return firstName;
} public void setFirstName(String firstName) {
this.firstName = firstName;
} public String getLastName() {
return lastName;
} public void setLastName(String lastName) {
this.lastName = lastName;
} private String firstName;
private String lastName; public Customer() {} public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
} @Override
public String toString() {
return String.format(
"Customer[id=%s, firstName='%s', lastName='%s']",
id, firstName, lastName);
}
}

操作类定义

package com.chzhao.mongodbtest;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;

public interface CustomerRepository extends MongoRepository<Customer, String> {

	public Customer findByFirstName(String firstName);

	public List<Customer> findByLastName(String lastName);

	public long deleteByFirstName(String firstName);

	public long countByLastName(String lastName);
}

调用方法

package com.chzhao.mongodbtest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; EnableAutoConfiguration
public class Application implements CommandLineRunner { @Autowired
private CustomerRepository repository; public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} public void run(String... args) throws Exception { for (int i = 0; i < 10000; i++) {
repository.save(new Customer(i + "", "zhao"));
}
long cou = repository.countByLastName("zhao");
System.out.println(cou); System.out.println("Customers found with findAll():");
System.out.println("-------------------------------");
for (Customer customer : repository.findAll()) {
System.out.println(customer);
}
System.out.println();
repository.deleteByFirstName("zhao"); // fetch an individual customer
System.out.println("Customer found with findByFirstName('Alice'):");
System.out.println("--------------------------------");
System.out.println(repository.findByFirstName("Alice")); System.out.println("Customers found with findByLastName('Smith'):");
System.out.println("--------------------------------");
for (Customer customer : repository.findByLastName("zhao")) {
System.out.println(customer);
} } }

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.chzhao</groupId>
<artifactId>mongodbtest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.4</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>1.1.10.RELEASE</version>
</dependency> </dependencies>
</project>

MongoOperations介绍

MongoOperations是一个很强大的接口,有了这个接口,基本上什么都搞定了。

其介绍

Interface that specifies a basic set of MongoDB operations. Implemented by {@link MongoTemplate}. Not often used but a useful option for extensibility and testability (as it can be easily mocked, stubbed, or be the target of a JDK proxy

直接上代码

实体类

package com.chzhao.mongodbtest;

import java.util.Date;

import org.springframework.data.annotation.Id;

public class Person {
public Person(String name, int age, Date birth) {
this.name = name;
this.age = age;
this.birth = birth;
} private Date birth; @Id
private String id; public Date getBirth() {
return birth;
} public void setBirth(Date birth) {
this.birth = birth;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} private String name; 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;
} private int age;
}

操作类

package com.chzhao.mongodbtest;

import static org.springframework.data.mongodb.core.query.Criteria.where;

import java.util.Date;
import java.util.List; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query; import com.mongodb.Mongo; public class MongoApp {
private static final Log log = LogFactory.getLog(MongoApp.class); public static void main(String[] args) throws Exception { MongoOperations mongoOps = new MongoTemplate(new Mongo(), "zch");
mongoOps.dropCollection(Person.class);
mongoOps.remove(new Query(where("name").is("zhao")), Person.class);
DateTime zhaoBirth = new DateTime(1985, 12, 13, 18, 23, 55);
DateTime liangBirth = new DateTime(1986, 12, 13, 18, 23, 55);
mongoOps.insert(new Person("zhao", 34, zhaoBirth.toDate()));
mongoOps.insert(new Person("liang", 24, liangBirth.toDate())); List<Person> pList = mongoOps.find(new Query(where("name").is("zhao")),
Person.class);
for (Person p : pList) {
log.info(p.getName() + p.getAge());
}
DateTime someday = new DateTime(1986, 1, 13, 18, 23, 55);
List<Person> pList1 = mongoOps.find(new Query(where("birth").lt(someday)), Person.class);
for (Person p : pList1) {
log.info(p.getName() + p.getAge());
} }
}

这个Query类似lambda表达式,能做很多事情,很赞。

MongoDB入门(7)- SpringDataMongoDB的更多相关文章

  1. MongoDB 入门之基础 DCL

    此文章主要记录部分主要的 MongoDB 的 DCL 操作. MongoDB 默认不需要用户名和密码就可以用 mongodb.exe 登录 一.开启 MonogoDB 的权限模式 修改 MongoDB ...

  2. MongoDB入门三:MongoDB shell

    MongoDB shell MongDB shell是一个功能完备的Javascript解释器,可以运行Javascript程序.也可以用于连接MongoDB服务器,执行脚本,对数据库进行操作.类似于 ...

  3. MongoDB 入门之查询(find)

    MongoDB 入门之查询(find) 1. find 简介 (1)find的第一个参数决定了要返回哪些文档. 空的查询文档会匹配集合的全部内容.默认就是{}.结果将批量返回集合c中的所有文档. db ...

  4. MongoDB入门简介

    MongoDB入门简介 http://blog.csdn.net/lolinzhang/article/details/4353699 有关于MongoDB的资料现在较少,且大多为英文网站,以上内容大 ...

  5. mongodb入门教程二

    title: mongodb入门教程二 date: 2016-04-07 10:33:02 tags: --- 上一篇文章说了mongodb最基本的东西,这边博文就在深入一点,说一下mongo的一些高 ...

  6. mongodb入门教程

    title: mongodb入门教程 date: 2016-04-06 14:47:18 tags: --- 为什么要认识呢,因为这玩意就一傻逼 借用一下百科的介绍 MongoDB 是一个介于关系数据 ...

  7. MongoDb 入门教程

    MongoDb 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的. 它是可扩展的高性能数据存储解决方案,经常被用于非关系型数据的存储,能存储海量的数据. 常 ...

  8. MongoDB入门必读(概念与实战并重)

    MongoDB入门必读(概念与实战并重) 一.概述 MongoDB是一个基于分布式文件存储的数据库开源项目.由C++语言编写.旨在为WEB应用提供可护展的高性能数据存储解决方案. MongoDB是一个 ...

  9. mongodb入门很简单(3)

     ##简单的mongodb入门命令## 1.show dbs;      //查看当前数据库 2.use databaseName;         //选库 3.show tables/collec ...

  10. MongoDB入门实践

    MongoDB入门实践 简单介绍MongoDB,包括MongoDB的使用场景.和MySQL的对比.安装部署.Java客户端访问及总结 MongoDB? 我们遵循需求驱动技术的原则,通过一个场景来引入M ...

随机推荐

  1. Kali信息收集-DNS

    1.whois查询 直接在终端输入whois 域名 2.查找dns服务器 (1)host (2)dig (3)nslookup 3.域传输 4.域名枚举 (1)dnsdict6 kali没有集成这款工 ...

  2. 适合初学者的嵌入式Linux计划

    俗话说万事开头难,刚开始的时候,你是否根本就不知如何开始,上网查资料被一堆堆新名词搞的找不到北,去图书馆看书也是找不到方向?又是arm,又是linux,又是uboot头都大了,不知道自己究竟从哪里开始 ...

  3. 域名加www与不加www不一样结果的解决办法

    有些浏览器域名访问加www 与不加www出现的页面不一样.在aj请求的时候也不同.firefox与google新版本的都会自动加上www. 比如 访问haitaohua.com,但aj请求的时候是带w ...

  4. 接口文档管理工具-Postman、Swagger、RAP(转载)

    接口文档管理工具-Postman.Swagger.RAP 转自:http://www.51testing.com/html/10/n-3715910.html 在项目开发测试中,接口文档是贯穿始终的. ...

  5. lintcode-160-寻找旋转排序数组中的最小值 II

    160-寻找旋转排序数组中的最小值 II 假设一个旋转排序的数组其起始位置是未知的(比如0 1 2 4 5 6 7 可能变成是4 5 6 7 0 1 2). 你需要找到其中最小的元素. 数组中可能存在 ...

  6. C++并行编程1

    what is concurrency 我们可以一边看电视,一边唱歌.人并行非常容易理解,但是计算机呢?是不是我们一边编辑着word文档,一边听着歌,这样计算机就是在并行吗?不一定欧,如果你计算机是单 ...

  7. Firefox火狐浏览器 修改默认搜索引擎

    如图:

  8. [计算机网络-传输层] 无连接传输:UDP

    UDP(用户数据报协议) 下面是UDP的报文段格式: 可以看出UDP的首部长度是固定的,共64bit,即8个字节. 校验和:提供了差错检测得功能,即用于确定当UDP报文段从源到达目的时,其中的比特是否 ...

  9. 按照list中实体类的某一属性排序

    传进一个装有实体类的list public void sort(List<MedicalPracticesDetail> mpdList){ Collections.sort(mpdLis ...

  10. Runtime之IMP指针,isa指针

    要了解 isa 指针先了解下类的定义在xcode中用快捷键Shift+Cmd+O 搜索objc.h 能看到类的定义:了解 Paste_Image.png 可以看出:objc_object:Object ...