文档章节

MongoDB学习笔记之 第4章 MongoDB整合Spring

黎明你好
 黎明你好
发布于 2017/08/09 10:44
字数 1178
阅读 5
收藏 0

 

MongoDB学习笔记之 第1章 MongoDB的安装

MongoDB学习笔记之 第2章 MongoDB的增删改查

MongoDB学习笔记之 第3章 MongoDB的Java驱动

MongoDB学习笔记之 第4章 MongoDB整合Spring

 

 第4章 MongoDB整合Spring

(黎明你好原创作品,转载请注明)

4.1 创建maven项目

4.1.1 repositories

创建maven项目,其中repositories使用spring的maven库:

 

<repositories>
	<repository>
		<id>central</id>
		<name>Maven Central</name>
		<url>http://repo1.maven.org/maven2/</url>
	</repository>
	<repository>
		<id>spring-release</id>
		<name>Spring Maven Release Repository</name>
		<url>http://repo.springsource.org/libs-release</url>
	</repository>
	<repository>
		<id>atlassian-m2-repository</id>
		<url>https://m2proxy.atlassian.com/repository/public</url>
	</repository>
</repositories>

 

4.1.2 Dependencies

使用到的jar包:

 

<dependencies>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<version>2.5</version>
		<type>jar</type>
		<scope>provided</scope>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-api</artifactId>
		<version>1.6.1</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-log4j12</artifactId>
		<version>1.7.5</version>
		<type>jar</type>
		<scope>runtime</scope>
	</dependency>
	<dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.10.1</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.data</groupId>
		<artifactId>spring-data-mongodb</artifactId>
		<version>1.2.1.RELEASE</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.data</groupId>
		<artifactId>spring-data-mongodb-cross-store</artifactId>
		<version>1.2.1.RELEASE</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
	<dependency>
		<groupId>org.springframework.data</groupId>
		<artifactId>spring-data-mongodb-log4j</artifactId>
		<version>1.2.1.RELEASE</version>
		<type>jar</type>
		<scope>compile</scope>
	</dependency>
</dependencies>

 

 

4.2 添加spring配置文件

spring的配置文件applicationContext.xml

 

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

	<context:component-scan base-package="liming.mongodb.example" />

	<mongo:mongo host="127.0.0.1" port="27017" />

	<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
	<mongo:db-factory dbname="student" mongo-ref="mongo" />

	<!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
	</bean>

	<!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
	<mongo:mapping-converter base-package="climing.mongodb.example.data.model" />

	<!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->
	<mongo:repositories base-package="liming.mongodb.example.data.impl" />

	<context:annotation-config />

</beans>

 

 

 

4.3 增删改查

Userl实现的增删改查:

4.3.1UserEntity

 

package liming.mongodb.example.data.model;

import java.util.Date;

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

@Document(collection = "user")
public class UserEntity {

	@Id
	private String id;
	private NameEntity name;
	private int age;
	private int works;
	private Date birth;
	private String password;
	private String regionName;
	private String[] special;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public NameEntity getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getWorks() {
		return works;
	}

	public void setWorks(int works) {
		this.works = works;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getRegionName() {
		return regionName;
	}

	public void setRegionName(String regionName) {
		this.regionName = regionName;
	}

	public String[] getSpecial() {
		return special;
	}

	public void setSpecial(String[] special) {
		this.special = special;
	}

}

 

 

4.3.2 NameEntity

 

package liming.mongodb.example.data.model;

public class NameEntity {

	private String username;

	private String nickname;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

}

 

 

4.3.3 UserDao

 

package liming.mongodb.example.data;

import java.util.List;

import liming.mongodb.example.data.model.UserEntity;

import org.springframework.transaction.annotation.Transactional;

@Transactional
public interface UserDao {

	public abstract void _test();

	public abstract void createCollection();

	public abstract List<UserEntity> findList(int skip, int limit);

	public abstract List<UserEntity> findListByAge(int age);

	public abstract UserEntity findOne(String id);

	public abstract UserEntity findOneByUsername(String username);

	public abstract void insert(UserEntity entity);

	public abstract void update(UserEntity entity);

}

 

 

4.3.4 UserDaoImpl

 

package liming.mongodb.example.data.impl;

import java.util.List;
import java.util.Set;

import liming.mongodb.example.data.UserDao;
import liming.mongodb.example.data.model.UserEntity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.mongodb.DB;

@Repository
public class UserDaoImpl implements UserDao {

	public static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public void _test() {
		Set<String> colls = this.mongoTemplate.getCollectionNames();
		for (String coll : colls) {
			logger.info("CollectionName=" + coll);
		}
		DB db = this.mongoTemplate.getDb();
		logger.info("db=" + db.toString());
	}

	@Override
	public void createCollection() {
		if (!this.mongoTemplate.collectionExists(UserEntity.class)) {
			this.mongoTemplate.createCollection(UserEntity.class);
		}
	}

	@Override
	public List<UserEntity> findList(int skip, int limit) {
		Query query = new Query();
		query.with(new Sort(new Order(Direction.ASC, "_id")));
		query.skip(skip).limit(limit);
		return this.mongoTemplate.find(query, UserEntity.class);
	}

	@Override
	public List<UserEntity> findListByAge(int age) {
		Query query = new Query();
		query.addCriteria(new Criteria("age").is(age));
		return this.mongoTemplate.find(query, UserEntity.class);
	}

	@Override
	public UserEntity findOne(String id) {
		Query query = new Query();
		query.addCriteria(new Criteria("_id").is(id));
		return this.mongoTemplate.findOne(query, UserEntity.class);
	}

	@Override
	public UserEntity findOneByUsername(String username) {
		Query query = new Query();
		query.addCriteria(new Criteria("name.username").is(username));
		return this.mongoTemplate.findOne(query, UserEntity.class);
	}

	@Override
	public void insert(UserEntity entity) {
		this.mongoTemplate.insert(entity);

	}

	@Override
	public void update(UserEntity entity) {
		Query query = new Query();
		query.addCriteria(new Criteria("_id").is(entity.getId()));
		Update update = new Update();
		update.set("age", entity.getAge());
		update.set("password", entity.getPassword());
		update.set("regionName", entity.getRegionName());
		update.set("special", entity.getSpecial());
		update.set("works", entity.getWorks());
		update.set("name", entity.getName());
		this.mongoTemplate.updateFirst(query, update, UserEntity.class);

	}

}

 

 

4.3.5 测试代码

 

package liming.mongodb.example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import liming.mongodb.example.data.UserDao;
import liming.mongodb.example.data.impl.UserDaoImpl;
import liming.mongodb.example.data.model.UserEntity;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationSpring {

	public static void main(String[] args) {

		System.out.println("Bootstrapping HelloMongo");

		ConfigurableApplicationContext context = null;
		context = new ClassPathXmlApplicationContext("applicationContext.xml");

		UserDao userDao = context.getBean(UserDaoImpl.class);
	        userDao._test();
		UserEntity entity1 = new UserEntity();
		entity1.setId("5");
		entity1.setAge(1);
		entity1.setBirth(new Date());
		entity1.setPassword("asdfasdf");
		entity1.setRegionName("北京");
		entity1.setWorks(1);
		userDao.insert(entity1);
		userDao.update(entity1);
		userDao.createCollection();
	
		List<UserEntity> list = userDao.findList(0, 10);
		for (UserEntity e : list) {
			System.out.println("all - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
					+ ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
		}

		list = userDao.findListByAge(1);
		for (UserEntity e : list) {
			System.out.println("age=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
					+ Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());
		}

		UserEntity e = userDao.findOne("1");
		System.out.println("id=1 - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special=" + Arrays.toString(e.getSpecial())
				+ ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());

		e = userDao.findOneByUsername("limingnihao");
		System.out.println("username=limingnihao - id=" + e.getId() + ", age=" + e.getAge() + ", password=" + e.getPassword() + ", regionName=" + e.getRegionName() + ", special="
				+ Arrays.toString(e.getSpecial()) + ", name=" + e.getName().getUsername() + "-" + e.getName().getNickname() + ", birth=" + e.getBirth());

		
		System.out.println("DONE!");
	}

}

 

 

本文转载自:http://limingnihao.iteye.com/blog/1940446

共有 人打赏支持
黎明你好
粉丝 1
博文 16
码字总数 2187
作品 1
朝阳
程序员
spring MVC 整合mongodb

Spring Mongodb 目录 1 SPRING整合MONGODB 1 1.1 环境准备 1 1.2 包依赖 1 1.3 配置 2 2 案列 5 2.1 SPRING MVC整合MONGODB代码案例 5 1 Spring整合Mongodb 1.1 环境准备 1. mongodb官网 ht...

浅夏
2014/03/13
0
0
spring项目整合mongodb进行开发

spring项目整合mongodb进行开发: MongoDB的性能指标: 100个并发,插入550万条记录的平均吞吐量:大约4100条/秒 MONGODB实际上是一个内存数据库,先将数据保存到内存,然后再写入磁盘中 1....

xiejunbo
2015/08/18
0
1
通过spring-data-mongodb 操作mongodb

一、前言 其实,以前项目组也使用过mongodb,只是那时候是作为主数据库来使用,所以在框架方面会更加复杂,比如使用jpa,如果只是把mongodb作为附数据库使用的话,个人认为通过spring-data-m...

漂泊者及其影子
2014/11/19
0
0
MongoDB在spring中xml传统配置

背景 旧项目中依然在使用springmvc的xml传统配置,最近需要使用MongoDB,需要在spring引入MongoDB的连接配置。 解决 配置mongodb数据库 配置mongodb数据工厂 配置mongodb的Template 配置mon...

亚林瓜子
06/12
0
0
Mongodb File Server 1.0.1,基于 Spring Boot 2.0.3

Mongodb File Server 更新到1.0.1,基于Spring Boot 2.0.3。详细更新如下: MongoDB 3.6.4 Spring Boot 2.0.3.RELEASE Spring Data MongoDB 2.0.8.RELEASE Spring 5.0.7.RELEASE Thymeleaf 3......

waylau
07/01
0
0

没有更多内容

加载失败,请刷新页面

加载更多

js 操作cookie

var cookie = {// 设置cookie方法set:function(key, val, time){// 获取当前时间var date = new Date();// 将date设置为n天以后的时间var expiresDays = time;//...

小丶二
42分钟前
1
0
限制root远程登录 su和sudo命令

9月21日任务 3.7 su命令 3.8 sudo命令 3.9 限制root远程登录 对于Linux而言,权限的重要性毋庸置疑!对于普通用户而言无法执行那些只有root用户才能有效的命令,导致工作无法有效进行; 系统...

robertt15
43分钟前
2
0
MQTT协议的初浅认识之通讯级别和持久会话

背景 这是我最近了解MQTT协议的最后一部分内容了,MQTT协议里面的QOS和Keep Alive是两个比较重要的内容。QOS的设置,直接影响了订阅客户端与中间件之间的消息交互行为。而Keep Alive直接影响...

亚林瓜子
46分钟前
2
0
calc

width: calc(100% - 30px); 特别注意:减号左右空格,均不能去掉。 width: calc(100% - 30px);

柴高八斗之父
54分钟前
1
0
Spring Cloud Gateway全局过滤器GlobalFilter:返回消息和重定向

Spring Cloud Gateway的全局过滤器GlobalFilter,顾名思义,声明后会对所有的请求生效,可以用来做权限控制,这里简单记录一下拦截到非法请求后如何返回自定义信息和将请求重定向到指定URL。...

夜雨寄北09
56分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部