Home Database Mysql Tutorial 使用spring连接及操作mongodb3.0

使用spring连接及操作mongodb3.0

Jun 07, 2016 pm 02:50 PM
spring use operate connect

前边有一篇记录过不使用spring,直接在java代码中连接和操作mongodb数据库,这里就紧随其后记录一下使用spring的情况下,在java中简单操作mongodb。 maven导包配置: 因为涉及了sping以及springmvc,因此也需要导入它们相关的包: project xmlns=http://maven

前边有一篇记录过不使用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></verbose>  
                      <bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jar</bootclasspath>  
                    </compilerarguments>  
                </configuration>
            </plugin>
        </plugins>
    <finalname>spring_mongo</finalname>
  </build>
</project>
Copy after login



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

    <!-- 自动扫描(自动注入) -->
    <component-scan base-package="spring_mogo.dao.daoImp"></component-scan>

    <!-- 导入mongodb的配置文件 -->
    <import resource="spring-mongodb305.xml"></import>

    <!-- 开启注解 -->
    <annotation-config></annotation-config>

</beans>
Copy after login


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-client host="192.168.0.201" port="27017" credentials="tuzongxun:123456@mongoTest" id="mongo">  
       <client-options write-concern="SAFE"></client-options>  
    </mongo-client> 

    <db-factory id="mongoDbFactory" dbname="mongoTest" mongo-ref="mongo"></db-factory>  

    <!-- 只要使用这个调用相应的方法操作 -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">  
       <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"></constructor-arg>  
    </bean>   

</beans>
Copy after login


与数据库对应的实体类: 需要注意的是这里需要实现序列化的接口并设置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;
    }

}
Copy after login


根据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);
    }
}
Copy after login



操作数据库的接口以及对应的实现类: 演示了最基础的增删改查,需要注意的地方在于参数的声明以及接收返回数据时和实体类的转换: (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);

}
</usermodel></usermodel></usermodel>
Copy after login


(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;
    }

}
</usermodel></usermodel></usermodel></usermodel>
Copy after login

测试类: 为了验证以上代码和配置的正确性,测试类代码如下:
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());
            }
        }
    }

}
</usermodel></usermodel>
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

As an industry leader, Spring+AI provides leading solutions for various industries through its powerful, flexible API and advanced functions. In this topic, we will delve into the application examples of Spring+AI in various fields. Each case will show how Spring+AI meets specific needs, achieves goals, and extends these LESSONSLEARNED to a wider range of applications. I hope this topic can inspire you to understand and utilize the infinite possibilities of Spring+AI more deeply. The Spring framework has a history of more than 20 years in the field of software development, and it has been 10 years since the Spring Boot 1.0 version was released. Now, no one can dispute that Spring

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

Three Ways to Fix Edge Your Connection Isn't Private Three Ways to Fix Edge Your Connection Isn't Private Mar 13, 2024 pm 01:30 PM

When you use the Edge browser to access web pages, have you ever encountered a prompt that your connection is not a dedicated connection, causing web browsing to fail? How is this going? Many friends don’t know how to deal with this problem. You can take a look at the following three solutions. Method 1 (simple and crude): In the edge browser, you can try to solve the problem of the website being inaccessible by entering the settings and turning off the security function, and then blocking location permissions in the website permissions. It is important to note that the effectiveness and duration of this approach may vary, and specific effects cannot be determined. After restarting your browser, you can try visiting the website to see if the issue is resolved. Method 2: Adjust the keyboard to English input

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

See all articles