Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 53 章 Spring Data with MongoDB

目录

53.1. Example Spring Data MongoDB
53.1.1. pom.xml
53.1.2. springframework-servlet.xml
53.1.3. POJO
53.1.4. Controller
53.1.5. 查看测试结果
53.1.6. 条件查询
53.2. MongoDB 多数据源
53.2.1. Maven
53.2.2. Application 禁止自动配置 MongoDB
53.2.3. application.properties 新增配置项
53.2.4. MongoDB 配置类
53.2.5. 创建 Document 关系映射类
53.2.6. 测试控制器
53.2.7. 测试
53.3. @Document
53.3.1. 指定表名
53.3.2. @Id
53.3.3. @Version
53.3.4. @Field 定义字段名
53.3.5. @Indexed
53.3.6. @CompoundIndex 复合索引
53.3.7. @TextIndexed
53.3.8. @GeoSpatialIndex 地理位置索引
53.3.9. @Transient 丢弃数据,不存到 mongodb
53.3.10. @DBRef 做外外键引用
53.3.11. @DateTimeFormat
53.3.12. @NumberFormat
53.3.13. 在 @Document 中使用 Enum 类型
53.3.14. 在 @Document 中定义数据结构 List/Map
53.3.15. GeoJson 数据类型
53.4. MongoRepository
53.4.1. 扫描仓库接口
53.4.2. findAll()
53.4.3. deleteAll()
53.4.4. save()
53.4.5. count()
53.4.6. exists() 判断是否存在
53.4.7. existsById()
53.4.8. findByXXXX
53.4.9. findAll with OrderBy
53.4.10. findAll with Sort
53.4.11. FindAll with Pageable
53.4.12. StartingWith 和 EndingWith
53.4.13. Between
53.4.14. Before / After
53.4.15. @Query
53.5. mongoTemplate
53.5.1. Save 保存
53.5.2. Insert
53.5.3. updateFirst 修改符合条件第一条记录
53.5.4. updateMulti 修改符合条件的所有
53.5.5. 查找并保存
53.5.6. upsert - 修改符合条件时如果不存在则添加
53.5.7. 删除
53.5.8. 查找一条数据
53.5.9. 查找所有数据
53.5.10. Query
53.5.11. Criteria
53.5.12. Update
53.5.13. BasicUpdate
53.5.14. Sort
53.5.15. Query + PageRequest
53.5.16. newAggregation
53.5.17. 创建索引
53.5.18. 子对象操作
53.6. GeoJson 反序列化
53.7. FAQ
53.7.1. location object expected, location array not in correct format; nested exception is com.mongodb.MongoWriteException: location object expected, location array not in correct format

https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/

53.1. Example Spring Data MongoDB

53.1.1. pom.xml

注意Spring4 与 1.9.1.RELEASE有兼容性问题,日志提示 Error creating bean with name 'mongoTemplate' defined in ServletContext resource

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

53.1.2. springframework-servlet.xml

			
	<mongo:db-factory id="mongoDbFactory" host="${mongo.host}" port="${mongo.port}" dbname="${mongo.database}" />
	<!-- username="${mongo.username}" password="${mongo.password}" -->

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
    
    <mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory"/>
    <bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
      <constructor-arg ref="mongoDbFactory"/>
      <constructor-arg ref="converter"/>
    </bean>
			
			

例 53.1. Spring Data MongoDB - springframework-servlet.xml

				
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/data/mongo
		http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd        
        ">

	<mvc:resources location="/images/" mapping="/images/**" />
	<mvc:resources location="/css/" mapping="/css/**" />
	<mvc:resources location="/js/" mapping="/js/**" />
	<mvc:resources location="/zt/" mapping="/zt/**" />
	<mvc:resources location="/sm/" mapping="/sm/**" />
	<mvc:resources location="/module/" mapping="/module/**" />

	<context:component-scan base-package="cn.netkiller.controller" />
	<!-- <context:property-placeholder location="classpath:resources/development.properties" /> -->
	<mvc:annotation-driven />

	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

	<bean id="configuracion" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:resources/development.properties" />
	</bean>
	
	<!-- MongoDB Connection Factory -->
	<mongo:db-factory id="mongoDbFactory" host="${mongo.host}" port="${mongo.port}" dbname="${mongo.database}" />
	<!-- username="${mongo.username}" password="${mongo.password}" -->
	
	<!-- MongoDB template definition -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
    
    <!-- MongoDB GridFS template definition -->
    <mongo:mapping-converter id="converter" db-factory-ref="mongoDbFactory"/>
    <bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
      <constructor-arg ref="mongoDbFactory"/>
      <constructor-arg ref="converter"/>
    </bean>
    
	<!-- Redis Connection Factory -->
	<bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:host-name="192.168.2.1" p:port="6379" p:use-pool="true" />

	<!-- redis template definition -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="jedisConnFactory" />
 
</beans>
				
				

development.properties 配置内容

			
mongo.host=192.168.4.1
mongo.port=27017
mongo.username=test
mongo.password=passw0rd
mongo.database=website
			
			

53.1.3. POJO

			
package cn.netkiller.pojo;

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

@Document(collection = "tracker")
public class Tracker {
	@Id
	private String id;
	private String name;
	private String unique;
	private String hostname;
	private String referrer;
	private String href;

	public Tracker() {
		// TODO Auto-generated constructor stub
	}

	public String getName() {
		return name;
	}

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

	public String getUnique() {
		return unique;
	}

	public void setUnique(String unique) {
		this.unique = unique;
	}

	public String getHostname() {
		return hostname;
	}

	public void setHostname(String hostname) {
		this.hostname = hostname;
	}

	public String getReferrer() {
		return referrer;
	}

	public void setReferrer(String referrer) {
		this.referrer = referrer;
	}

	public String getHref() {
		return href;
	}

	public void setHref(String href) {
		this.href = href;
	}

	@Override
	public String toString() {
		return "Tracker [id=" + id + ", name=" + name + ", unique=" + unique + ", hostname=" + hostname + ", referrer=" + referrer + ", href=" + href + "]";
	}

}		
			
			

53.1.4. Controller

			
package cn.netkiller.controller;

import cn.netkiller.pojo.Tracker;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@Controller
public class TrackerController {

	@Autowired
	private MongoTemplate mongoTemplate;

	public TrackerController() {

	}

	@RequestMapping("/tracker/test")
	@ResponseBody
	String hello() {
		return "Hello World!";
	}

	@RequestMapping("/tracker")
	@ResponseBody
	String execute() {
		Tracker tracker = new Tracker();
		tracker.setName("test");
		tracker.setUnique("111223456");
		tracker.setHostname("www.example.com");
		tracker.setHref("http://example.com/test.html");
		tracker.setReferrer("http://example.com/");
		this.mongoTemplate.insert(tracker);
		
		return tracker.toString();
	}

}
			
			

53.1.5. 查看测试结果

			
> db.tracker.find();
{ "_id" : ObjectId("5757c0b92c526a6bda5eea3a"), "_class" : "cn.netkiller.repositories.Tracker", "name" : "test", "unique" : "111223456", "hostname" : "www.example.com", "referrer" : "http://example.com/", "href" : "http://example.com/test.html" }

			
			

53.1.6. 条件查询

			
	@RequestMapping("/read/name/{name}")
	public ArrayList<Tracker> sort(@PathVariable String name) {
	
		Query query = new Query(Criteria.where("name").is(name)); 
		 
		ArrayList<Tracker> trackers =  (ArrayList<Tracker>) mongoTemplate.find(query, Tracker.class);
		return trackers;
	}