SpringDataMongoDB介绍(一)-入门
SpringDataMongoDB介绍(一)-入门
本文介绍如何应用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
 
准备工作
需要事先安装mongodb数据库,其下载地址
示例代码
实体类定义
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>
参考
SpringDataMongoDB介绍(一)-入门的更多相关文章
- .NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(一)
		
在文章:这些.NET开源项目你知道吗?让.NET开源来得更加猛烈些吧!(第二辑)中,给大家初步介绍了一下FluentValidation验证组件.那里只是概述了一下,并没有对其使用和强大功能做深入研究 ...
 - freemarker语法介绍及其入门教程实例
		
# freemarker语法介绍及其入门教程实例 # ## FreeMarker标签使用 #####一.FreeMarker模板文件主要有4个部分组成</br>#### 1.文本,直接输 ...
 - (转)私有代码存放仓库 BitBucket介绍及入门操作
		
转自:http://blog.csdn.net/lhb_0531/article/details/8602139 私有代码存放仓库 BitBucket介绍及入门操作 分类: 研发管理2013-02-2 ...
 - NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(转载)
		
原文地址:http://www.cnblogs.com/asxinyu/p/dotnet_Opensource_project_FluentValidation_1.html 阅读目录 1.基本介绍 ...
 - 读写Word的组件DocX介绍与入门
		
本文为转载内容: 文章原地址:http://www.cnblogs.com/asxinyu/archive/2013/02/22/2921861.html 开源Word读写组件DocX介绍与入门 阅读 ...
 - [转帖]Druid介绍及入门
		
Druid介绍及入门 2018-09-19 19:38:36 拿着核武器的程序员 阅读数 22552更多 分类专栏: Druid 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议 ...
 - Redis介绍及入门安装及使用
		
Redis介绍及入门安装及使用 什么是Redis Redis is an open source (BSD licensed), in-memory data structure store, use ...
 - Mysql数据库的简单介绍与入门
		
Mysql数据库的简单介绍与入门 前言 一.下载与安装 1.下载 官网下载MYSQL5.7.21版本,链接地址https://www.mysql.com/downloads/.下载流程图如下: 找到M ...
 - Nodejs学习笔记(十四)— Mongoose介绍和入门
		
目录 简介 mongoose安装 连接字符串 Schema Model 常用数据库操作 插入 更新 删除 条件查询 数量查询 根据_id查询 模糊查询 分页查询 其它操作 写在之后... 简介 Mon ...
 
随机推荐
- HDU 4565 So Easy!(矩阵)
			
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4565 题意: 题意: #include <iostream>#include <cs ...
 - 关于引用mshtml的问题
			
今天看了个验证码识别的代码,其中引用到了mshtml.dll,找了半天原来就是microsoft.mshtml.dll.查这个dll的时候还发现了好几篇关于这个dll添加问题的文章.顺便看了下,原来这 ...
 - mac 下php运行bug
			
如下所说bug在window下没有,在mac下存在. mac下的php报如下错误: fopen("data.json") Error: failed to open stream: ...
 - httpRequest对象常用的方法
			
IT程序员开发必备-各类资源下载清单,史上最全IT资源,个人收藏总结! 1. 获得客户机信息 getRequestURL方法返回客户端发出请求时的完整URL. getRequestURI方 ...
 - JAVA操作Excel 可配置,动态 生成复杂表头 复杂的中国式报表表头
			
转载:开源社区http://www.oschina.net/code/snippet_1424099_49530?p=2代码] [Java]代码 该代码实现了Excel复杂表头的生成 基于sql se ...
 - Codeforces Round #232 (Div. 2)  B. On Corruption and Numbers
			
题目:http://codeforces.com/contest/397/problem/B 题意:给一个n ,求能不能在[l, r]的区间内的数字相加得到, 数字可多次重复.. 比赛的时候没有想出来 ...
 - Asp.Net IEnumerable,ICollection,IList,List区别
			
做C#的同学们,都知道,一类只能有一个继承类,但可以实现多个接口.这句话就告诉我们:IEnumerable,ICollection,IList,List区别了 首先我看看 IEnumerable: / ...
 - ionic安装拍照选照片插件
			
1.安装插件,也可以用ionic plugin add .... phonegap local plugin add https://git-wip-us.apache.org/repos/asf/c ...
 - OpenGL 顶点缓存对象
			
顶点缓存对象(Vertex Buffer Object,简称 VBO),允许开发者根据情况把顶点数据放到显存中. 如果不用 VBO,用 glVertexPointer / glNormalPointe ...
 - 【C#学习笔记】打开新进程
			
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...