solr测试项目(中)--整合spring-data-mongo

接着solr测试项目(上)–基于maven的springmvc环境搭建
我们已经把一个简单的springmvc环境搭建好,下面我们开始整合spring-data-mongo。

整合spring-data-mongo

参考Ubuntu 14.04 LTS 安装 MongoDB
先将mongo数据库搭建好。

这里采用spring提供的MongoTemplate来操作。

依赖

将spring和spring-data的版本采用bom管理起来

<properties>
    <spring-version>4.2.5.RELEASE</spring-version>
    <releasetrain-version>Hopper-SR3</releasetrain-version>
</properties>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>${spring-version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-releasetrain</artifactId>
            <version>${releasetrain-version}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

最终的spring依赖和spring-data-mongodb和mongod的java驱动依赖如下

<!-- spring依赖 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
</dependency>
<!-- spring依赖的第三方 -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>
<!-- mongo数据库需要 -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
</dependency>
<!-- mongodb驱动 -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.3.0</version>
</dependency>

配置文件

在src/main/resources/spring下建一个spring-dao.xml主要用来配置数据库的

spring-dao.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:p="http://www.springframework.org/schema/p"
    xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    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/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 1.加载配置文件 -->
    <context:property-placeholder 
        location="classpath:mongo.properties"
        file-encoding="utf-8" 
        ignore-unresolvable="true" />
    <!-- 2.定义 mongo连接属性 -->
    <mongo:mongo-client id="mongo" host="${mongo.host}" port="${mongo.port}">
        <mongo:client-options 
            connections-per-host="${mongo.connectionsPerHost}"
            threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
            connect-timeout="${mongo.connectTimeout}" 
            max-wait-time="${mongo.maxWaitTime}"
            socket-keep-alive="${mongo.socketKeepAlive}"
            socket-timeout="${mongo.socketTimeout}" />
    </mongo:mongo-client>
    <!-- 3.定义一个 mongo连接工厂并指定数据库名称,我的数据库是mylearn,如果没有会创建 -->
    <mongo:db-factory id="mongoDbFactory" dbname="mylearn" mongo-ref="mongo" />
    <!-- 4.定义mongoTemplate -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>
</beans>

在src/main/resources下建一个配置文件mongo.properties

mongo.properties

mongo.host=你的mongo数据库的地址
mongo.port=27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
mongo.connectTimeout=1000
mongo.maxWaitTime=1500
mongo.socketKeepAlive=true
mongo.socketTimeout=1500

导入spring-dao.xml
在spring-core.xml中导入spring-dao.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.gwc.learn" />
    <import resource="classpath:spring/spring-dao.xml" />
</beans>

测试

测一下增删改查,其他的参考官方文档。

测试之前先把日志弄好

#------------------------------------------------------------------------------------
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
#   1. DEBUG (the least serious)
#   2. INFO
#   3. WARN
#   4. ERROR
#   5. FATAL (the most serious)
#
#------------------------------------------------------------------------------------
# 日志输出级别
#------------------------------------------------------------------------------------
log4j.rootLogger=info, stdout, info_log, error_log

#------------------------------------------------------------------------------------
# 输出到控制台
#------------------------------------------------------------------------------------
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS} %p [%M] %c %L %m%n
#log4j.appender.stdout.layout=org.apache.log4j.TTCCLayout

#------------------------------------------------------------------------------------
# info_log
#------------------------------------------------------------------------------------
log4j.appender.info_log=org.apache.log4j.DailyRollingFileAppender
log4j.appender.info_log.File=/usr/logs/learn/info.log
log4j.appender.info_log.Append=true
log4j.appender.info_log.Threshold=INFO
log4j.appender.info_log.layout=org.apache.log4j.PatternLayout
log4j.appender.info_log.DatePattern='.'yyyy-MM-dd
log4j.appender.info_log.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS} %p [%M] %c %L %m%n

#------------------------------------------------------------------------------------
# error_log
#------------------------------------------------------------------------------------
log4j.appender.error_log=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error_log.File=/usr/logs/learn/error.log
log4j.appender.error_log.Append=true
log4j.appender.error_log.Threshold=ERROR
log4j.appender.error_log.layout=org.apache.log4j.PatternLayout
log4j.appender.error_log.DatePattern='.'yyyy-MM-dd
log4j.appender.error_log.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss:SSS} %p [%M] %c %L %m%n

#------------------------------------------------------------------------------------
# 我的配置
#------------------------------------------------------------------------------------
log4j.category.org.springframework=info
log4j.category.org.springframework.data.mongodb=DEBUG

Person对象

package com.gwc.learn.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "person")
public class Person {
    @Id
    private String id;
    private String name;
    private int age;

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    // 省去getter setter和toString()方法
}

测试用例

package test;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Update.update;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.gwc.learn.entity.Person;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-dao.xml")
public class HelloTest {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void test() {
        // 先把数据清空
        mongoTemplate.dropCollection(Person.class);

        Person person = new Person("程高伟", 18);
        // 增
        mongoTemplate.insert(person);
        // 查
        Person personFind = mongoTemplate.findById(person.getId(), Person.class);
        logger.info("findById:{}", personFind);
        // 改
        mongoTemplate.updateFirst(new Query(where("name").is("程高伟")), update("age", 20), Person.class);
        // 该之后再查
        personFind = mongoTemplate.findById(person.getId(), Person.class);
        logger.info("修改之后:{}", personFind);
        // 删
        mongoTemplate.remove(person);

        Person anotherPerson = new Person("张三", 18);
        Person anotherPerson1 = new Person("张三", 18);
        mongoTemplate.insert(anotherPerson);
        mongoTemplate.insert(anotherPerson1);
        // 查询所有
        logger.info("findAll:{}",mongoTemplate.findAll(Person.class));


    }

}

日记输出

这里写图片描述

数据库记录

这里写图片描述

参考文献

  1. Ubuntu 14.04 LTS 安装 MongoDB

  2. Spring Data MongoDB - Reference Documentation

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页