Spring3+Spring-data-mongodb1.5.6示例

17 篇文章 0 订阅
1 篇文章 0 订阅

A: maven2 pom.xml

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.5.6.RELEASE</version>
        </dependency>
        <!-- bean validate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2</version>
        </dependency>

说明:

1 . 为什么Spring-data-mongodb的版本是1.5.6?

这个版本对应的Spring-data版本是1.4.6,对应的Spring-framework版本是3.2.14,大于此版本需要spring-framework 4,从这个地址可以知道:
Spring-data-parent.pom

2. 为什么还需要hibernate-validator?

缺少这个依赖会抛以下异常:

Caused by: javax.validation.ValidationException: Unable to create a Configuration, because no Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath.
    at javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:271)
    at org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:191)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1573)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1511)

B: spring的配置文件

<?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:util="http://www.springframework.org/schema/util"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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.2.xsd
          http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
          http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
">
    <!-- 加载配置属性文件 -->
    <util:properties id="propertyConfigurer" location="classpath:spring-data-mongo.properties" />
    <context:property-placeholder ignore-unresolvable="true" properties-ref="propertyConfigurer" />

    <context:annotation-config />
    <!-- spring data -->
    <mongo:mongo host="${mongo.host}" port="${mongo.port}" />

    <mongo:db-factory dbname="${mongo.database}" mongo-ref="mongo" />

    <!-- set the mapping converter to be used by the MongoTemplate -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>

    <bean class="org.springframework.data.mongodb.core.mapping.event.LoggingEventListener" />

    <bean id="forumMemberOnlineService" class="net.htage.lab.cache.mongo.ForumMemberOnlineMongo">
        <property name="mongoTemplate" ref="mongoTemplate" />
    </bean>
</beans>

C: 实体和实现类

import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Field;
/**
 *
 * @author xiaofanku@live.cn
 * @since 20170908
 */
@Document(collection = "apo_forum_online")
public class ForumMemberOnline implements Serializable{
    @Id
    private String ID;
    @Indexed
    @Field
    private int memberId=0;
    @Indexed
    @Field
    private int uid=0;
    @Indexed
    @Field
    private String sessionId;
    @Field
    private String nickname="guest";
    //GET/SET
}
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
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;
/**
 *
 * @author xiaofanku@live.cn
 * @since 20170908
 */
public class ForumMemberOnlineMongo implements ForumMemberOnlineService{
    private static final Logger logger=LoggerFactory.getLogger(ForumMemberOnlineMongo.class);
    private MongoTemplate mongoTemplate;

    @Override
    public ForumMemberOnline save(ForumMemberOnline entity) {
        try{
            logger.error("[OLD]session:"+entity.getSessionId());

            mongoTemplate.insert(entity);
            logger.error("[OLD]id:"+entity.getID());
            return entity;
        }catch(Exception e){
            throw new NullPointerException();
        }
    }
    //ETC
}

说明:

1. mongoTemplate.insert方法会返回@Id注解的属性
2. 无法对实体作注解,可以使用转换器

实体

/**
 *
 * @author xiaofanku@live.cn
 * @since 20170908
 */
public class ForumMemberOnline implements Serializable{
    private Long ID;
    private int memberId=0;
    private int uid=0;
    private String sessionId;
    private String nickname="guest";
    //GET/SET
}

转换器

/**
 * 
 * mongodb 出库时使用
 * @author xiaofanku@live.cn
 * @since 20170908
 */
public class ForumMemberOnlineReadConverter implements Converter<BasicDBObject, ForumMemberOnline>{
    private static final Logger logger=LoggerFactory.getLogger(ForumMemberOnlineReadConverter.class);
    @Override
    public ForumMemberOnline convert(BasicDBObject doc) {
        logger.error("converting read start");
        ForumMemberOnline fmo=new ForumMemberOnline();
        fmo.setID(doc.getLong("_id"));
        fmo.setMemberId(doc.getInt("memberId"));
        fmo.setUid(doc.getInt("uid"));
        fmo.setSessionId(doc.getString("sessionId"));
        fmo.setNickname(doc.getString("nickname"));
        return fmo;
    }

}
/**
 * mongodb 入库时转换
 * @author xiaofanku@live.cn
 * @since 20170908
 */
public class ForumMemberOnlineWriteConverter implements Converter<ForumMemberOnline, DBObject>{
    private static final Logger logger=LoggerFactory.getLogger(ForumMemberOnlineWriteConverter.class);

    @Override
    public DBObject convert(ForumMemberOnline fmo) {
        logger.error("converting write start");
        DBObject dbo = new BasicDBObject();
        if(fmo.getID()>0){
            dbo.put("_id", fmo.getID());
        }
        dbo.put("memberId", fmo.getMemberId());
        dbo.put("uid", fmo.getUid());
        dbo.put("sessionId", fmo.getSessionId());
        dbo.put("nickname", fmo.getNickname());
        return dbo;
    }
}

Spring 配置中增加

    <mongo:mapping-converter>
        <mongo:custom-converters>
            <mongo:converter>
                <bean class="package.ForumMemberOnlineReadConverter "/>
            </mongo:converter>
            <mongo:converter>
                <bean class="package.ForumMemberOnlineWriteConverter "/>
            </mongo:converter>
        </mongo:custom-converters>
    </mongo:mapping-converter>

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

附注:需要自已解决ID的生成, mongodb的实现参考:Spring Data MongoDB – Auto Sequence ID example

mongodb生成的_id是一个数字和字母混合的字符序列, 也可以使用java来解决

D: 最后

[1]. 文档参考地址: Spring Data MongoDB - Reference Documentation
[2]. 在线API: Spring Data MongoDB 1.5.6.RELEASE API
[3]. 完整的pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>net.htage</groupId>
    <artifactId>lab</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>lab</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!--spring framework-->
        <spring-framework.version>3.2.14.RELEASE</spring-framework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.5.6.RELEASE</version>
        </dependency>
        <!-- java unit test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-framework.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- Logging with SLF4J & Log4J -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
        <!-- bean validate-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.2.Final</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>el-impl</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

这里写图片描述

完整的示例下载地址:Baidu网盘

[4]. 同时使用JPA(不是Spring-data-jpa)+Spring-data-mongodb无法同时工作

正常DEBUG:

DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class net.htage.lab.entity.ForumMemberOnline for index information.

不能工作的DEBUG:

DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.tools.schemaframework.ForeignKeyConstraint for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.tools.schemaframework.IndexDefinition for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.internal.helper.DatabaseTable for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.internal.helper.DatabaseField for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.mappings.AttributeAccessor for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.mappings.DatabaseMapping for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.mappings.querykeys.QueryKey for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class interface org.eclipse.persistence.sessions.changesets.UnitOfWorkChangeSet for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class interface org.eclipse.persistence.sessions.changesets.ObjectChangeSet for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class interface org.eclipse.persistence.sessions.changesets.ChangeRecord for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.internal.sessions.ChangeRecord for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class interface org.eclipse.persistence.exceptions.ExceptionHandler for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.exceptions.IntegrityChecker for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class class org.eclipse.persistence.sequencing.Sequence for index information.
DEBUG [org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexCreator] - Analyzing class interface org.eclipse.persistence.mappings.converters.Converter for index information.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值