欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用spring连接及操作mongodb3.0实例

程序员文章站 2024-03-11 15:30:19
前边有一篇记录过不使用spring,直接在java代码中连接和操作mongodb数据库,这里就紧随其后记录一下使用spring的情况下,在java中简单操作mongodb。...

前边有一篇记录过不使用spring,直接在java代码中连接和操作mongodb数据库,这里就紧随其后记录一下使用spring的情况下,在java中简单操作mongodb。

maven导包配置:

因为涉及了sping以及springmvc,因此也需要导入它们相关的包:

<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/maven-v4_0_0.xsd"> 
 <modelversion>4.0.0</modelversion> 
 <groupid>spring_mongo</groupid> 
 <artifactid>spring_mongo</artifactid> 
 <packaging>war</packaging> 
 <version>0.0.1-snapshot</version> 
 <name>spring_mongo maven webapp</name> 
 <url>http://maven.apache.org</url> 
 <dependencies> 
  <dependency> 
    <groupid>org.springframework.data</groupid> 
    <artifactid>spring-data-mongodb</artifactid> 
    <version>1.8.0.release</version> 
  </dependency> 
  <dependency> 
    <groupid>org.mongodb</groupid> 
    <artifactid>mongo-java-driver</artifactid> 
    <version>3.0.3</version> 
  </dependency> 
  <dependency> 
    <groupid>commons-logging</groupid> 
    <artifactid>commons-logging</artifactid> 
    <version>1.2</version> 
  </dependency> 
  <dependency> 
    <groupid>org.springframework</groupid> 
    <artifactid>spring-test</artifactid> 
    <version>4.1.6.release</version> 
  </dependency> 
  <dependency> 
    <groupid>junit</groupid> 
    <artifactid>junit</artifactid> 
    <version>4.11</version> 
  </dependency> 
  <dependency> 
    <groupid>org.springframework</groupid> 
    <artifactid>spring-context</artifactid> 
    <version>4.1.7.release</version> 
  </dependency> 
  <dependency> 
    <groupid>org.springframework</groupid> 
    <artifactid>spring-context-support</artifactid> 
    <version>4.0.9.release</version> 
  </dependency> 
 </dependencies> 
 <build> 
 <plugins> 
      <plugin> 
        <artifactid>maven-compiler-plugin</artifactid> 
        <version>2.3.2</version> 
        <configuration> 
          <source>1.7</source> 
          <target>1.7</target> 
          <encoding>utf-8</encoding> 
          <compilerarguments>  
           <verbose />  
           <bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>  
          </compilerarguments>  
        </configuration> 
      </plugin> 
    </plugins> 
  <finalname>spring_mongo</finalname> 
 </build> 
</project> 

spring基础配置:

主要是开启注解扫描等:

<?xml version="1.0" encoding="utf-8"?> 
<beans xmlns:task="http://www.springframework.org/schema/task" 
  xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 
  xmlns:context="http://www.springframework.org/schema/context" 
  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-3.0.xsd 
http://www.springframework.org/schema/task 
http://www.springframework.org/schema/task/spring-task-3.1.xsd"> 
 
  <!-- 自动扫描(自动注入) --> 
  <context:component-scan base-package="spring_mogo.dao.daoimp" /> 
 
  <!-- 导入mongodb的配置文件 --> 
  <import resource="spring-mongodb305.xml" /> 
 
  <!-- 开启注解 --> 
  <context:annotation-config /> 
 
</beans> 

spring连接mongodb以及建立相关工厂的配置:

<?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:p="http://www.springframework.org/schema/p" 
  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.xsd"> 
 
  <!-- spring连接mongodb数据库的配置 --> 
  <mongo:mongo-client host="192.168.0.201" port="27017" credentials="tuzongxun:123456@mongotest" id="mongo">  
    <mongo:client-options write-concern="safe"/>  
  </mongo:mongo-client>  
 
  <mongo:db-factory id="mongodbfactory" dbname="mongotest" mongo-ref="mongo" />  
 
  <!-- 只要使用这个调用相应的方法操作 --> 
  <bean id="mongotemplate" class="org.springframework.data.mongodb.core.mongotemplate">  
    <constructor-arg name="mongodbfactory" ref="mongodbfactory" />  
  </bean>   
 
</beans> 

与数据库对应的实体类:

需要注意的是这里需要实现序列化的接口并设置uid的属性,否则不能在操作中直接把数据库返回结果转换成对象属性:

package spring_mongo.models; 
 
import java.io.serializable; 
 
public class usermodel implements serializable { 
 
  private static final long serialversionuid = 1l; 
  private string username; 
  private string password; 
 
  public usermodel(string username, string password) { 
    super(); 
    this.username = username; 
    this.password = password; 
  } 
 
  public string getusername() { 
    return username; 
  } 
 
  public void setusername(string username) { 
    this.username = username; 
  } 
 
  public string getpassword() { 
    return password; 
  } 
 
  public void setpassword(string password) { 
    this.password = password; 
  } 
 
} 

根据spring配置获取操作mongodb的mongotemplete,需要实现applicationcontextaware接口:

package spring_mogo.dao.daoimp; 
 
import org.springframework.beans.beansexception; 
import org.springframework.context.applicationcontext; 
import org.springframework.context.applicationcontextaware; 
import org.springframework.data.mongodb.core.mongotemplate; 
 
public abstract class abstractbasemongotemplete implements 
    applicationcontextaware { 
 
  protected mongotemplate mongotemplate; 
 
  /** 
   * @description 根据配置文件设置mongotemplate 
   * @param mongotemplate 
   */ 
  public void setmongotemplate(mongotemplate mongotemplate) { 
    this.mongotemplate = mongotemplate; 
  } 
 
  @override 
  public void setapplicationcontext(applicationcontext applicationcontext) 
      throws beansexception { 
    mongotemplate mongotemplate = applicationcontext.getbean( 
        "mongotemplate", mongotemplate.class); 
    setmongotemplate(mongotemplate); 
  } 
} 

操作数据库的接口以及对应的实现类:

演示了最基础的增删改查,需要注意的地方在于参数的声明以及接收返回数据时和实体类的转换:

(1)接口:

package spring_mogo.dao; 
 
import java.util.list; 
 
import spring_mongo.models.usermodel; 
 
public interface userdao { 
  /** 
   * 查询数据 
   * 
   * @author:tuzongxun 
   * @title: findall 
   * @param @return 
   * @return list<usermodel> 
   * @date may 13, 2016 3:07:39 pm 
   * @throws 
   */ 
  public list<usermodel> findall(); 
 
  /** 
   * 新增数据 
   * 
   * @author:tuzongxun 
   * @title: insertuser 
   * @param @param user 
   * @return void 
   * @date may 13, 2016 3:09:45 pm 
   * @throws 
   */ 
  public void insertuser(usermodel user); 
 
  /** 
   * 删除数据 
   * 
   * @author:tuzongxun 
   * @title: removeuser 
   * @param @param username 
   * @return void 
   * @date may 13, 2016 3:09:55 pm 
   * @throws 
   */ 
  public void removeuser(string username); 
 
  /** 
   * 修改数据 
   * 
   * @author:tuzongxun 
   * @title: updateuser 
   * @param @param user 
   * @return void 
   * @date may 13, 2016 3:10:06 pm 
   * @throws 
   */ 
  public void updateuser(usermodel user); 
 
  /** 
   * 按条件查询 
   * 
   * @author:tuzongxun 
   * @title: findforrequery 
   * @param 
   * @return void 
   * @date may 13, 2016 3:23:37 pm 
   * @throws 
   */ 
  public list<usermodel> findforrequery(string username); 
 
} 

(2)实现类,这里要继承abstractbasemongotemplete类,从而获得mongotemplete进行各种操作:

package spring_mogo.dao.daoimp; 
 
import java.util.list; 
 
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 spring_mogo.dao.userdao; 
import spring_mongo.models.usermodel; 
 
import com.mongodb.basicdbobject; 
import com.mongodb.dbobject; 
 
@component("userdaoimp") 
public class userdaoimp extends abstractbasemongotemplete implements userdao { 
 
  /** 
   * 查询所有数据 
   * 
   * @author:tuzongxun 
   * @title: findall 
   * @description: todo 
   * @param @return 
   * @date may 13, 2016 3:10:29 pm 
   * @throws 
   */ 
  @override 
  public list<usermodel> findall() { 
    // 需要设置集合对应的尸体类和相应的集合名,从而查询结果直接映射 
    list<usermodel> userlist = mongotemplate.findall(usermodel.class, 
        "user"); 
    return userlist; 
  } 
 
  /** 
   * 新增数据 
   * 
   * @author:tuzongxun 
   * @title: insertuser 
   * @description: todo 
   * @param @param user 
   * @date may 13, 2016 3:10:45 pm 
   * @throws 
   */ 
  @override 
  public void insertuser(usermodel user) { 
    // 设置需要插入到数据库的文档对象 
    dbobject object = new basicdbobject(); 
    object.put("username", user.getusername()); 
    object.put("password", user.getpassword()); 
    mongotemplate.insert(object, "user"); 
  } 
 
  /** 
   * 按条件删除数据 
   * 
   * @author:tuzongxun 
   * @title: removeuser 
   * @description: todo 
   * @param @param username 
   * @date may 13, 2016 3:11:01 pm 
   * @throws 
   */ 
  @override 
  public void removeuser(string username) { 
    // 设置删除条件,如果条件内容为空则删除所有 
    query query = new query(); 
    criteria criteria = new criteria("username"); 
    criteria.is(username); 
    query.addcriteria(criteria); 
    mongotemplate.remove(query, "user"); 
  } 
 
  /** 
   * 修改数据 
   * 
   * @author:tuzongxun 
   * @title: updateuser 
   * @description: todo 
   * @param @param user 
   * @date may 13, 2016 3:11:12 pm 
   * @throws 
   */ 
  @override 
  public void updateuser(usermodel user) { 
    // 设置修改条件 
    query query = new query(); 
    criteria criteria = new criteria("username"); 
    criteria.is(user.getusername()); 
    query.addcriteria(criteria); 
    // 设置修改内容 
    update update = update.update("password", user.getpassword()); 
    // 参数:查询条件,更改结果,集合名 
    mongotemplate.updatefirst(query, update, "user"); 
  } 
 
  /** 
   * 根据条件查询 
   * 
   * @author:tuzongxun 
   * @title: findforrequery 
   * @description: todo 
   * @param @param username 
   * @date may 13, 2016 4:08:15 pm 
   * @throws 
   */ 
  @override 
  public list<usermodel> findforrequery(string username) { 
    query query = new query(); 
    criteria criteria = new criteria("username"); 
    criteria.is(username); 
    query.addcriteria(criteria); 
    // 查询条件,集合对应的实体类,集合名 
    list<usermodel> userlist = mongotemplate.find(query, usermodel.class, 
        "user"); 
    return userlist; 
  } 
 
} 

测试类:

为了验证以上代码和配置的正确性,测试类代码如下:

package spring_mongo.test; 
 
import java.util.list; 
 
import org.junit.test; 
import org.junit.runner.runwith; 
import org.springframework.beans.factory.annotation.autowired; 
import org.springframework.test.context.contextconfiguration; 
import org.springframework.test.context.junit4.springjunit4classrunner; 
 
import spring_mogo.dao.userdao; 
import spring_mongo.models.usermodel; 
 
@runwith(springjunit4classrunner.class) 
@contextconfiguration(locations = { "classpath:spring.xml" }) 
public class mongotest { 
 
  @autowired 
  private userdao userdao; 
 
  /** 
   * 查询测试 
   * 
   * @author:tuzongxun 
   * @title: monfindtest 
   * @param 
   * @return void 
   * @date may 13, 2016 3:27:51 pm 
   * @throws 
   */ 
  @test 
  public void monfindtest() { 
    list<usermodel> usermodels = userdao.findall(); 
    if (usermodels != null && usermodels.size() > 0) { 
      for (usermodel user : usermodels) { 
        system.out.println(user.getusername() + ":" 
            + user.getpassword()); 
      } 
    } 
  } 
 
  /** 
   * 插入数据测试 
   * 
   * @author:tuzongxun 
   * @title: moninserttest 
   * @param 
   * @return void 
   * @date may 13, 2016 3:27:38 pm 
   * @throws 
   */ 
  @test 
  public void moninserttest() { 
    usermodel user = new usermodel("test111", "123456"); 
    userdao.insertuser(user); 
    this.monfindtest(); 
  } 
 
  /** 
   * 删除测试 
   * 
   * @author:tuzongxun 
   * @title: monremovetest 
   * @param 
   * @return void 
   * @date may 13, 2016 3:28:06 pm 
   * @throws 
   */ 
  @test 
  public void monremovetest() { 
    string username = "test111"; 
    userdao.removeuser(username); 
    this.monfindtest(); 
  } 
 
  /** 
   * 测试修改 
   * 
   * @author:tuzongxun 
   * @title: monupdatetest 
   * @param 
   * @return void 
   * @date may 13, 2016 3:50:08 pm 
   * @throws 
   */ 
  @test 
  public void monupdatetest() { 
    usermodel user = new usermodel("test111", "test"); 
    userdao.updateuser(user); 
    this.monfindtest(); 
  } 
 
  /** 
   * 按条件查询 
   * 
   * @author:tuzongxun 
   * @title: monfindforruq 
   * @param 
   * @return void 
   * @date may 13, 2016 4:10:53 pm 
   * @throws 
   */ 
  @test 
  public void monfindforruq() { 
    string username = "test111"; 
    list<usermodel> usermodels = userdao.findforrequery(username); 
    if (usermodels != null && usermodels.size() > 0) { 
      for (usermodel user : usermodels) { 
        system.out.println(user.getusername() + ":" 
            + user.getpassword()); 
      } 
    } 
  } 
 
} 

后期补上demo下载地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。