即日起在codingBlog上分享您的技术经验即可获得积分,积分可兑换现金哦。

Maven_Spring_Mongo 实例

编程语言 zhiguoliu11 76℃ 0评论

环境:Vmware Workstation 10,CentOS-7-x86_64-DVD-1511.iso,Xshell 4.0,ip:192.168.216.140.


这里写图片描述

User.java

package com.demo.mongo.bean;

import org.springframework.stereotype.Component;

@Component
public class User {

    private String username;
    private String password;

    public User() {
        super();
    }

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

    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + "]";
    }

}

ApplicationContextUtil.java

package com.demo.mongo.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextUtil {
    private static final ApplicationContext APPLICATION_CONTEXT;

    static {
        APPLICATION_CONTEXT = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
    }

    public static ApplicationContext getApplicationContext() {
        return APPLICATION_CONTEXT;
    }

    public static  T getBean(String name, Class requiredType)
            throws BeansException {
        return APPLICATION_CONTEXT.getBean(name, requiredType);
    }

    public static void main(String[] args) {
        System.out.println(ApplicationContextUtil.APPLICATION_CONTEXT);
    }

}

MongoUtil.java

package com.demo.mongo.util;

import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.mongodb.DB;

public class MongoUtil {

    private static final MongoTemplate MONGO_TEMPLATE;

    static {
        MONGO_TEMPLATE = ApplicationContextUtil.getBean("mongoTemplate", MongoTemplate.class);
    }

    public static DB getDB() {
        return MONGO_TEMPLATE.getDb();
    }

    public static void save(Object object) {
        MONGO_TEMPLATE.save(object);
    }

    public static  boolean exists(Class entityClass) {
        return MONGO_TEMPLATE.collectionExists(entityClass);
    }

    public static long count(Query query, Class entityClass) {
        return MONGO_TEMPLATE.count(query, entityClass);
    }

    public static  List findAll(Class entityClass) {
        return MONGO_TEMPLATE.findAll(entityClass);
    }

    public static  T findOne(Query query, Class entityClass) {
        return MONGO_TEMPLATE.findOne(query, entityClass);
    }

    public static  T findAndModify(Query query, Update update, Class entityClass) {
        return MONGO_TEMPLATE.findAndModify(query, update, entityClass);
    }

    public static  T findAndRemove(Query query, Class entityClass) {
        return MONGO_TEMPLATE.findAndRemove(query, entityClass);
    }

    public static MongoTemplate getMongo() {
        return MONGO_TEMPLATE;
    }

}

applicationContext.xml


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

    <import resource="mongod.xml" />

beans>

log4j.properties


logdir= jingyu_server_logs/
#logdir=D:/remote/jingyu

# Global logging configuration,  debug < info < warn < error < fatal
# log4j.rootLogger = [debug], [info], [warn], [error], [fatal], [stdout]
log4j.rootLogger=debug, stdout, debug, info, error
log4j.logger.com.jiaoyinbrother=debug, command

# Console output
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold = INFO
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyy-MM-dd HH:mm:ss } [%t] %5p %c{1}:%L - %m%n

# debug output
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.MaxFileSize=10MB
log4j.appender.debug.MaxBackupIndex=10
log4j.appender.debug.Threshold = DEBUG
log4j.appender.debug.File=${logdir}/debug.txt
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=%d %-5p (%13F:%L) %3x - %m%n

# info output
log4j.appender.info=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info.MaxFileSize=10MB
log4j.appender.info.MaxBackupIndex=10
log4j.appender.info.Threshold = INFO
log4j.appender.info.File=${logdir}/info.txt
log4j.appender.info.layout=org.apache.log4j.PatternLayout
log4j.appender.info.layout.ConversionPattern=%d %-5p (%13F:%L) %3x - %m%n

# error output
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.MaxFileSize=10MB
log4j.appender.error.MaxBackupIndex=10
log4j.appender.error.Threshold = ERROR
log4j.appender.error.File=${logdir}/error.txt
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d %-5p (%13F:%L) %3x - %m%n

# command output
log4j.appender.command=org.apache.log4j.DailyRollingFileAppender
log4j.appender.command.MaxFileSize=10MB
log4j.appender.command.MaxBackupIndex=10
log4j.appender.command.Threshold = INFO
log4j.appender.command.File=${logdir}/command.txt
log4j.appender.command.layout=org.apache.log4j.PatternLayout
log4j.appender.command.layout.ConversionPattern=%d %-5p (%13F:%L) %3x - %m%n

mongod.xml


<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:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util" 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.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/context/spring-jee.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

    <mongo:mongo id="mongo" host="192.168.216.140" port="27017" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongo" />
        <constructor-arg value="demo" />
    bean>

beans>

MongoTest.java

package com.demo.mongo.test;

import java.util.List;

import org.junit.Test;
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 com.demo.mongo.bean.User;
import com.demo.mongo.util.MongoUtil;

public class MongoTest {
    @Test
    public void mongo() {

        // DB name
        System.out.println("DB name: " + MongoUtil.getDB());

        // 添加数据
        User user = new User("zhaoliu", "554322");
        MongoUtil.save(user);

        // 判断collection是否存在
        System.out.println(MongoUtil.exists(User.class));

        // 查询所有
        System.out.println("size: " + MongoUtil.count(new Query(), User.class));
        List users = MongoUtil.findAll(User.class);
        for (User user1 : users) {
            System.out.println(user1);
        }

        // 查询指定元素
        System.out.println("------------------------------------------------");
        Query query = new Query(Criteria.where("username").is("zhaoliu"));
        user = MongoUtil.findOne(query, User.class);
        System.out.println(user);

        // 修改元素
        System.out.println("------------------------------------------------");
        Update update = new Update().set("password", "222222");// 修改
        // Update update = new Update().update("password", "111111");//修改
        MongoUtil.findAndModify(query, update, User.class);

        user = MongoUtil.findOne(query, User.class);
        System.out.println(user);

        // 删除一个元素
        System.out.println("------------------------------------------------");
        MongoUtil.findAndRemove(query, User.class);
        System.out.println("size: " + MongoUtil.count(new Query(), User.class));
    }

}

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.0modelVersion>
    <groupId>com.demogroupId>
    <artifactId>maven-spring-mongoartifactId>
    <version>0.0.1-SNAPSHOTversion>

    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.slf4jgroupId>
            <artifactId>slf4j-log4j12artifactId>
            <version>1.7.12version>
        dependency>

        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>4.3.0.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframework.datagroupId>
            <artifactId>spring-data-mongodbartifactId>
            <version>1.10.3.RELEASEversion>
        dependency>

        
        
        
        
        

    dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.5.1version>
                <configuration>
                    <source>1.7source>
                    <target>1.7target>
                    <encoding>UTF-8encoding>
                configuration>
            plugin>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-source-pluginartifactId>
                <version>3.0.1version>
                <executions>
                    <execution>
                        <id>attach-sourcesid>
                        <goals>
                            <goal>jargoal>
                        goals>
                    execution>
                executions>
            plugin>
        plugins>
    build>
project>

maven-spring-mongo 实例源码

转载请注明:CodingBlog » Maven_Spring_Mongo 实例

喜欢 (0)or分享 (0)
发表我的评论
取消评论

*

表情