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

第 78 章 Spring Data with MongoDB

目录

78.1. Example Spring Data MongoDB
78.1.1. pom.xml
78.1.2. springframework-servlet.xml
78.1.3. POJO
78.1.4. Controller
78.1.5. 查看测试结果
78.1.6. 条件查询
78.2. MongoDB 多数据源
78.2.1. Maven
78.2.2. Application 禁止自动配置 MongoDB
78.2.3. application.properties 新增配置项
78.2.4. MongoDB 配置类
78.2.5. 创建 Document 关系映射类
78.2.6. 测试控制器
78.2.7. 测试
78.3. @Document
78.3.1. 指定表名
78.3.2. @Id
78.3.3. @Version
78.3.4. @Field 定义字段名
78.3.5. @Indexed
78.3.6. @CompoundIndex 复合索引
78.3.7. @TextIndexed
78.3.8. @GeoSpatialIndex 地理位置索引
78.3.9. @Transient 丢弃数据,不存到 mongodb
78.3.10. @DBRef 做外外键引用
78.3.11. @DateTimeFormat
78.3.12. @NumberFormat
78.3.13. 在 @Document 中使用 Enum 类型
78.3.14. 在 @Document 中定义数据结构 List/Map
78.3.15. GeoJson 数据类型
78.4. MongoRepository
78.4.1. 扫描仓库接口
78.4.2. findAll()
78.4.3. deleteAll()
78.4.4. save()
78.4.5. count()
78.4.6. exists() 判断是否存在
78.4.7. existsById()
78.4.8. findByXXXX
78.4.9. findAll with OrderBy
78.4.10. findAll with Sort
78.4.11. FindAll with Pageable
78.4.12. StartingWith 和 EndingWith
78.4.13. Between
78.4.14. Before / After
78.4.15. @Query
78.5. mongoTemplate
78.5.1. Save 保存
78.5.2. Insert
78.5.3. updateFirst 修改符合条件第一条记录
78.5.4. updateMulti 修改符合条件的所有
78.5.5. 查找并保存
78.5.6. upsert - 修改符合条件时如果不存在则添加
78.5.7. 删除
78.5.8. 查找一条数据
78.5.9. 查找所有数据
78.5.10. Query
78.5.11. Criteria
78.5.12. Update
78.5.13. BasicUpdate
78.5.14. Sort
78.5.15. Query + PageRequest
78.5.16. newAggregation
78.5.17. 创建索引
78.5.18. 子对象操作
78.6. GeoJson 反序列化
78.7. FAQ
78.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/

78.1. Example Spring Data MongoDB

78.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>			
			
			

78.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>
			
			

例 78.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
			
			

78.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 + "]";
	}

}		
			
			

78.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();
	}

}
			
			

78.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" }

			
			

78.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;
	}