使用JAVA操作MongoDB(Spring整合)

Spring-mongoDB.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:aop="http://www.springframework.org/schema/aop" 
 xmlns:tx="http://www.springframework.org/schema/tx"  
 xmlns:mvc="http://www.springframework.org/schema/mvc"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 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/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.0.xsd   
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <!-- mongodb 的基本配置 -->
    
    <mongo:mongo id="mongo"  host="127.0.0.1" port="27017"  />
    
    <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 --> 
    <mongo:db-factory id="mongoDbFactory" dbname="test" mongo-ref="mongo" username="root" password="root"  />
    
    <bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />  
    <!-- 配置mongodb映射类型 -->  
    <bean id="mappingMongoConverter" class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">  
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />  
        <constructor-arg name="mappingContext" ref="mappingContext" />  
        <property name="typeMapper" ref="defaultMongoTypeMapper" />  
    </bean>  
  
    <!-- 默认Mongodb类型映射 -->  
    <bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">  
        <constructor-arg name="typeKey">  
            <null /><!-- 这里设置为空,可以把 spring data mongodb 多余保存的_class字段去掉 -->  
        </constructor-arg>  
    </bean>  
    
    <!-- 操作mongodb -->
    <!-- mongodb的主要操作对象mongoTemplate(Spring Data提供),所有对mongodb的增删改查的操作都是通过它完成 -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>
    
    <context:component-scan base-package="cn.dao.impl"></context:component-scan>
    
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID">
	<display-name>1108MongoDB</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<!-- 启动spring -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-mongodb.xml</param-value>
	</context-param>
	<!-- applicationContext -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>


dao层

package cn.dao;

import java.util.List;

import cn.pojo.ems;

public interface EmsDao {
	/**
	 * 查询单个员工信息
	 * @return
	 */
	ems getEms(String name);
	/**
	 * 查询所有员工集合
	 * @return
	 */
	List<ems> getAllEms();
	/**
	 * 更新员工信息
	 * @return
	 */
	int update(String name);
	/**
	 * 新增员工信息
	 */
	void insert(ems e);
	/**
	 * 删除员工信息
	 * @return
	 */
	int delEms(String name);
}
Dao实现类

package cn.dao.impl;

import java.util.List;

import javax.annotation.Resource;

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.Component;

import com.mongodb.WriteResult;

import cn.dao.EmsDao;
import cn.pojo.ems;
@Component
public class EmsDaoImpl implements EmsDao {
	//注意要引入注解	
	@Resource(name="mongoTemplate")
	MongoTemplate mongoTemplate;
	/**
	 * 查询单个
	 * @param name
	 * @return
	 */
	@Override
	public ems getEms(String name) {
		Criteria criteria = new Criteria();
		// 使用where和is设置要匹配的key和value
		criteria.where("name").is(name);
		// 将条件添加进Query里
		Query query = new Query();
		query.addCriteria(criteria);
		// 使用方法查询,Students.class是用实体类的名字取匹配mongodb的集合名
		ems findOne = mongoTemplate.findOne(query, ems.class);
		// mongodb通过实体的属性名自动匹配属性
		return findOne;
	}
	/**
	 * 查询所有
	 * @return
	 */
	@Override
	public List<ems> getAllEms() {
		List<ems> findAll = mongoTemplate.findAll(ems.class);
		return findAll;
	}
	/**
	 * 更新
	 * @param name
	 * @return
	 */
	@Override
	public int update(String name) {
		Query query = new Query();
		query.addCriteria(Criteria.where("name").is(name));
		
		Update up = new Update();
		up.set("age", 130);
		WriteResult multi = mongoTemplate.updateMulti(query, up, ems.class);
		System.out.println(multi.getN());
		return multi.getN();
	}
	/**
	 * 插入
	 * @param e
	 */
	@Override
	public void insert(ems e) {
		mongoTemplate.insert(e);
		System.out.println(e.get_id());
	}
	/**
	 * 删除
	 * @param name
	 * @return
	 */
	@Override
	public int delEms(String name) {
		Query query = new Query();
		query.addCriteria(Criteria.where("name").is(name));
		
		WriteResult multi = mongoTemplate.remove(query, ems.class);
		System.out.println(multi.getN());
		return multi.getN();
	}

}
pojo

package cn.pojo;

public class ems {
	private String _id;		//职工ID
	private String name;	//职工姓名
	private String job;		//职位
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getJob() {
		return job;
	}
	public void setJob(String job) {
		this.job = job;
	}
	
	public String get_id() {
		return _id;
	}
	public void set_id(String _id) {
		this._id = _id;
	}
	@Override
	public String toString() {
		return "ems [_id=" + _id + ", name=" + name + ", job=" + job + "]";
	}
	
}

测试类

package cn.dao.impl;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.dao.EmsDao;
import cn.pojo.ems;

public class EmsDaoImplTest {
	
	@Test
	public void test(){
		//测试前需要先设置读取配置文件
		ApplicationContext acx = new ClassPathXmlApplicationContext("spring-mongodb.xml");
		EmsDao m = (EmsDao) acx.getBean("emsDaoImpl");
		
		/*ems ems = m.getEms("张三");
		System.out.println(ems);*/
		
		/*List<ems> allEms = m.getAllEms();
		for (ems ems : allEms) {
			System.out.println(ems.getName());
		}*/
		
		/*int update = m.update("张三");
		System.out.println(update);*/
		
		/*ems e = new ems();
		e.setJob("白领");
		e.setName("老二");
		m.insert(e);*/
		
		m.delEms("老二");
	}

}

使用maven创建的项目,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.test</groupId>
  <artifactId>1108MongoDB</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <build/>
  <dependencies>
	<!-- MyBatis Generator -->
		<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
		<dependency>
		    <groupId>org.mybatis.generator</groupId>
		    <artifactId>mybatis-generator-core</artifactId>
		</dependency>
	
	<!-- Spring MVC -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-webmvc</artifactId>
		</dependency>
	
	<!-- Spring单元测试 -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-test</artifactId>
		    <scope>test</scope>
		</dependency>
	
	
	<!-- Spring JDBC -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		</dependency>
		
	<!-- Spring 面向切面 -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-aspects</artifactId>
		</dependency>
	
	<!-- MyBatis -->
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		</dependency>
		
	<!-- MyBatis 整合 Spring 的包 -->	
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		</dependency>
	
	<!-- 数据库连接池、驱动 -->	
		<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
		<dependency>
		    <groupId>c3p0</groupId>
		    <artifactId>c3p0</artifactId>
		    <version>0.9.0</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java -->
		<dependency>
		    <groupId>com.mchange</groupId>
		    <artifactId>mchange-commons-java</artifactId>
		</dependency>
		
		
	<!-- MyBatis 整合 Spring 的包 -->	
		<!-- https://mvnrepository.com/artifact/jstl/jstl -->
		<dependency>
		    <groupId>jstl</groupId>
		    <artifactId>jstl</artifactId>
		</dependency>
	
	<!-- servlet API包 -->	
		<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>javax.servlet-api</artifactId>
		    <scope>provided</scope>
		</dependency>
		
	<!-- 单元测试包 -->
		<!-- https://mvnrepository.com/artifact/junit/junit -->
		<dependency>
		    <groupId>junit</groupId>
		    <artifactId>junit</artifactId>
		    <scope>test</scope>
		</dependency>
	
	<!-- Mongodb -->
	<dependency>
	    <groupId>org.springframework.data</groupId>
	    <artifactId>spring-data-mongodb</artifactId>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
	<dependency>
	    <groupId>org.mongodb</groupId>
	    <artifactId>mongo-java-driver</artifactId>
	</dependency>
	
	
	
	
  </dependencies>
  <dependencyManagement>
  	<dependencies>
  		<dependency>
  			<groupId>org.mybatis.generator</groupId>
  			<artifactId>mybatis-generator-core</artifactId>
  			<version>1.3.5</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-webmvc</artifactId>
  			<version>4.3.7.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-test</artifactId>
  			<version>4.3.7.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-jdbc</artifactId>
  			<version>4.3.7.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework</groupId>
  			<artifactId>spring-aspects</artifactId>
  			<version>4.3.7.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.mybatis</groupId>
  			<artifactId>mybatis</artifactId>
  			<version>3.4.2</version>
  		</dependency>
  		<dependency>
  			<groupId>org.mybatis</groupId>
  			<artifactId>mybatis-spring</artifactId>
  			<version>1.3.1</version>
  		</dependency>
  		<dependency>
  			<groupId>mysql</groupId>
  			<artifactId>mysql-connector-java</artifactId>
  			<version>5.1.41</version>
  		</dependency>
  		<dependency>
  			<groupId>com.mchange</groupId>
  			<artifactId>mchange-commons-java</artifactId>
  			<version>0.2.12</version>
  		</dependency>
  		<dependency>
  			<groupId>jstl</groupId>
  			<artifactId>jstl</artifactId>
  			<version>1.2</version>
  		</dependency>
  		<dependency>
  			<groupId>javax.servlet</groupId>
  			<artifactId>javax.servlet-api</artifactId>
  			<version>3.0.1</version>
  		</dependency>
  		<dependency>
  			<groupId>junit</groupId>
  			<artifactId>junit</artifactId>
  			<version>4.12</version>
  		</dependency>
  		<dependency>
  			<groupId>org.springframework.data</groupId>
  			<artifactId>spring-data-mongodb</artifactId>
  			<version>1.7.2.RELEASE</version>
  		</dependency>
  		<dependency>
  			<groupId>org.mongodb</groupId>
  			<artifactId>mongo-java-driver</artifactId>
  			<version>2.14.2</version>
  		</dependency>
  		
  	</dependencies>
  </dependencyManagement>
</project>



微信扫码订阅
UP更新不错过~
关注
  • 1
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论

打赏作者

Aaryn30

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值