入门

本文介绍如何应用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. 脚本 script 常用脚本

    目录 remove_all_pyc find_all_links rename_with_slice load_json_without_dupes execution_time benchmark_ ...

  2. crt0.S(_main)代码分析

    crt0,S(_main)代码分析 --- 1. 设置sp寄存器地址 //设置SP栈指针 #if defined(CONFIG_SPL_BUILD) && defined(CONFIG ...

  3. MyBatis中文文档

    http://mybatis.github.io/mybatis-3/zh/index.html

  4. vue移动音乐app开发学习(三):轮播图组件的开发

    本系列文章是为了记录学习中的知识点,便于后期自己观看.如果有需要的同学请登录慕课网,找到Vue 2.0 高级实战-开发移动端音乐WebApp进行观看,传送门. 完成后的页面状态以及项目结构如下: 一: ...

  5. Oil Deposits(DFS连通图)

    Description The GeoSurvComp geologic survey company is responsible for detecting underground oil dep ...

  6. Java学习个人备忘录之关键字final

    final关键字final可以修饰类,方法,变量.final修饰的类不可以被继承final修饰的方法不可以被覆盖final修饰的变量是一个常量.只能被赋值一次.内部类只能访问被final修饰的局部变量 ...

  7. lintcode-185-矩阵的之字型遍历

    185-矩阵的之字型遍历 给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历. 样例 对于如下矩阵: [ [1, 2, 3, 4], [5, 6, 7, 8], [9 ...

  8. DAY1敏捷冲刺

    站立式会议 工作安排 (1)服务器配置 (2)数据库建表 (3)页面初步样式设计 (4)主要页面之间的交互 燃尽图 代码提交记录 感想 林一心:后端云服务器的配置确实是一个挑战,目前还在摸索中 赵意: ...

  9. Qt Creator子目录项目-类似VS解决方案

    版权声明:若无来源注明,Techie亮博客文章均为原创. 转载请以链接形式标明本文标题和地址: 本文标题:Qt Creator子目录项目-类似VS解决方案     本文地址:http://techie ...

  10. #Leetcode# 951. Flip Equivalent Binary Trees

    https://leetcode.com/problems/flip-equivalent-binary-trees/ For a binary tree T, we can define a fli ...