Spring3+Spring-data-mongodb1.5.6示例

来源:互联网 发布:iphone软件下载 编辑:程序博客网 时间:2024/06/05 23:44

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.
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 在食品厂上班載卫生帽头发痒怎么办 工司没给员工上保险离职后怎么办 货物被香港律政司扣了怎么办 室友考研要跟我考一样的学校怎么办 药流第一天才吃了一粒米非司怎么办 药流半月同房第二天大出血怎么办 口臭想让它变得不臭怎么办 来单位干了几天不满意想离职怎么办 药流吃药期间吃什么吐什么怎么办 养狗家里味道大怎么办养花有用吗 第一天上班站的脚疼怎么办 入职没有人事所需要的证书怎么办 入职第一天后不想去了怎么办 警察在执法过程中殴打群众怎么办 肾结石打了3天针痛得厉害怎么办 征兵体检过了到部队退兵怎么办 圆通快递要求退回结果被签收怎么办 新生儿蛋蛋淹了破皮了怎么办 要是和同学玩的时候打到睾丸怎么办 睾丸撞了一下里面碎了怎么办 睾丸被蚊子咬了挠坏流水疼怎么办 沐浴乳大量的灌注到尿道里怎么办 当电脑显示有文件损害时怎么办? 电脑上的压缩包手机上打不开怎么办 第五人格多酷账号退出了怎么办 更新显卡驱动时屏幕关闭了怎么办 不知道杯孕做了两次C丁怎么办 小说签约后更不到要求的字数怎么办 电脑中了感染病毒杀不干净怎么办 电脑下载的软件有病毒了怎么办 电脑强制关机后开不了机怎么办 受刺激后出现精神异常该怎么办 当屏幕出现暂时无法移动时怎么办 英雄联盟欧服连接不上服务器怎么办 试客联盟认证手机号成空号了怎么办 汽车脚垫不贴合翘起来了怎么办 版权保护迅雷下载不了的资源怎么办 30岁在外地城市找不到工作怎么办 新买的苹果爱拍充不进去电是怎么办 绝地求生东南亚服匹配不到人怎么办 电脑卡住了怎么办鼠标也点不动