Java操作mongodb数据库



引子

  前面演示了mongodb单机环境的搭建和集群环境的搭建,在实际开发中,我们是通过程序来操作mongodb数据库中的数据的。对mongodb数据库的操作和其他数据库一样,无外乎增删改查,这节我们通过java语言来演示下怎么操作mongodb数据库.

开发工具

   Eclipse
   Maven
   这里使用eclipse创建项目,使用maven引入mongodb操作的jar包,使用spring-data-mongodb包,这个是spring提供的对mongodb进行操作的包,包中提供了MongoTemplate模板类来对数据库进行增删改查操作
  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.mongodb</groupId>
  <artifactId>mongodbdemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>mongodbdemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.1.RELEASE</version>
</dependency>
		
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
  </dependencies>
</project>

数据操作

    这里演示下怎样向mongodb中scm数据库中的products表进行增删改查.首先创建一个Products对象,包括商品编码,商品名称
   注:id对象在插入的时候不需要赋值,mongodb会自动生成
Products.java
/**
 * 
 */
package com.mongodb;

public class Products {

	public String id;
	
	public String code;
	
	public String name;
	
	public String getId() {
		return id;
	}

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

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

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

	
}
定义连接mongodb数据库的配置文件spring-mongodb.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/data/mongo   
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd   
          http://www.springframework.org/schema/beans   
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<!-- 集群配置 -->
	<mongo:mongo id="mongo"	replica-set="192.168.159.135:27017,192.168.159.136:27017,192.168.159.137:27017">
		<mongo:options connections-per-host="8"
			threads-allowed-to-block-for-connection-multiplier="4"
			connect-timeout="1000" max-wait-time="1500" auto-connect-retry="true"
			socket-keep-alive="true" socket-timeout="3000" slave-ok="true"
			write-number="1" write-timeout="0" write-fsync="true" />
	</mongo:mongo>

<!-- 单机配置 -->
<!-- 	<mongo:mongo id="mongo"	host="192.168.159.135" port="27017"> -->
<!-- 		<mongo:options connections-per-host="8" -->
<!-- 			threads-allowed-to-block-for-connection-multiplier="4" -->
<!-- 			connect-timeout="1000" max-wait-time="1500" auto-connect-retry="true" -->
<!-- 			socket-keep-alive="true" socket-timeout="3000" slave-ok="true" -->
<!-- 			write-number="1" write-timeout="0" write-fsync="true" /> -->
<!-- 	</mongo:mongo> -->

	<mongo:db-factory id="mongoDbFactory" dbname="scm"	username="dba" password="dba" mongo-ref="mongo" />

	<bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
	<!-- 去掉_class属性 -->
	<bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
		<constructor-arg name="typeKey">
			<null />
		</constructor-arg>
	</bean>

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

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
		<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
	</bean>
	
</beans>

创建spring.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:tx="http://www.springframework.org/schema/tx"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


	<context:annotation-config/>
	<import resource="classpath:spring-mongodb.xml" />
	<context:component-scan base-package="com.mongodb" />
		

</beans>

创建操作数据库的dao层 DataDao.java
/**
 * 
 */
package com.mongodb;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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;



@Component
public class DataDao {

	@Autowired
	private MongoTemplate mongoTemplate;
	
	/**
	 * 
	 * TODO(添加) 
	 *
	 * @author 
	 * @param products        
	 * @date 2016年10月24日 下午5:30:38
	 */
	public void insert(Products products) {
		
		mongoTemplate.insert(products);
	}
	
	/**
	 * 
	 * TODO(查询所有) 
	 *
	 * @author 
	 * @return        
	 * @date 2016年10月24日 下午5:31:02
	 */
	public List<Products> QueryAll() {
		return mongoTemplate.findAll(Products.class);
	}
	
	/**
	 * 
	 * TODO(删除) 
	 *
	 * @author 
	 * @param id        
	 * @date 2016年10月24日 下午5:31:16
	 */
	public void delete(String id) {
		
	Query query = new Query();
	query.addCriteria(Criteria.where("id").is(id));
	mongoTemplate.remove(query, Products.class);
		
	}
	
	/**
	 * 
	 * TODO(更新) 
	 *
	 * @author
	 * @param products        
	 * @date 2016年10月25日 下午4:53:28
	 */
	public void updateCode(Products products) {
		
		 Query query = new Query();  
		  query.addCriteria(Criteria.where("code").is(products.code));
		 mongoTemplate.updateFirst(query, new Update().set("name",products.name),
				 Products.class);
	}
	
	public Products findOne(String id) {

		return mongoTemplate.findById(id, Products.class);
	}
   
}

启动项目,调用Dao层的增删改查方法
APP.JAVA
package com.mongodb;

import java.awt.List;
import java.util.ArrayList;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	try
    	{
    		    System.out.println("初始化配置文件");
    		    ApplicationContext appContext=new ClassPathXmlApplicationContext("spring.xml");  
    		   // MongoTemplate mongoTemplate=(MongoTemplate)appContext.getBean("mongoTemplate");
    		    DataDao dao = (DataDao)appContext.getBean("dataDao");
    	        
    		    System.out.println("插入数据");
    	        //插入
    	        Products products=new Products();
    	        products.code="0001";
    	        products.name="上衣";
    	        dao.insert(products);
    	
    	        System.out.println("查询");
    	        //查询
    	        ArrayList<Products> list=(ArrayList<Products>) dao.QueryAll();
    	        System.out.println(list.size());
    	        
    	        //删除
    	        if (list.size()>0)
    	        {
					
    	           System.out.println("删除");	
    	        	
       	         dao.delete(list.get(0).id);
				}
    	       
    	         
    	        System.out.println("修改");
    	         Products p1=new Products();
    	         p1.code="0001";
    	         p1.name="裤子";
    	         //修改
    	         dao.updateCode(p1);
    	         
    	         //查询单个实体
    	         Products  p=dao.findOne("580dd42871f9a08a424e07da");
    	         if (p!=null) {
					System.out.println(p.getCode()+"--"+p.getName()+"--"+p.getId());
				}
    	         
    	         System.out.println("执行成功");
    	        
    	}
    	catch(Exception e)
    	{
    		
    		System.out.println("执行异常"+e.getMessage());
    	}
     
    	
        
    }
}

发布了299 篇原创文章 · 获赞 116 · 访问量 95万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览