Spring项目接入MongoDB

前言

由于今日公司mysql数据库压力过大,由部分数据打算迁移至mongoDb,在此做个记录。

配置

pom文件中增加配置:

--

点击查看代码
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>2.14.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>

这里需要注意下你的Spring版本的兼容情况,我的项目Spring版本为4.2.5。Spring版本兼容情况如下:

Spring Data MongoDB 1.8.0.RELEASE 1.9.0.RELEASE 1.9.4.RELEASE 1.9.9.RELEASE 2.0.0.RELEASE 2.1.9.RELEASE 3.0.3.RELEASE
mongo-java-driver 2.13.0 2.14.0 2.14.3 2.14.3 3.5.0 3.5.0 3.5.0
Spring Framework 4.1.7.RELEASE 4.2.5.RELEASE 4.2.8.RELEASE 4.3.13.RELEASE 5.0.0.RELEASE 5.1.8.RELEASE 5.2.8.RELEASE

参考链接:Spring Data MongoDB 与 mongo java driver 与 spring Framework 的版本兼容情况

properties配置:

--

点击查看代码
mongo.hostport=127.0.0.1:27017
mongo.host=127.0.0.1
mongo.port=27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#连接超时时间
mongo.connectTimeout=1000
#等待时间
mongo.maxWaitTime=1500
#Socket超时时间
mongo.socketTimeout=1500
#admin登录信息
mongo.username=mongoadmin
mongo.password=mongoadmin
#DataBaseName
#认证数据库名
mongo.authenticationDbname=admin

#要链接的数据库名
mongo.databaseName=ttt

--

servlet.xml中配置:

--
mongo-client的写法:

点击查看代码
    <mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" credentials="${mongo.username}:${mongo.password}@${mongo.authenticationDbname}">
        <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="true"
                              socket-timeout="${mongo.socketTimeout}"
        />
    </mongo:mongo-client>
    <!--   使用用户名密码 -->
    <mongo:db-factory id="mongoDbFactory" dbname="${mongo.databaseName}" mongo-ref="mongoClient"/>
    <bean id="MongoTemplate"
          class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>

--

如果是老版mongo的写法为(此写法已过时):

点击查看代码
    <!-- 下面是mongo的方式 -->
        <mongo:mongo replica-set="${mongo.hostport}">
            <mongo: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="true"
                           socket-timeout="${mongo.socketTimeout}"
                           slave-ok="true"
                           write-number="1"
                           write-timeout="0"
                           write-fsync="true"              />
        </mongo:mongo>
        <mongo:db-factory username="${mongo.username}" password="${mongo.password}"
                          dbname="${mongo.databaseName}" mongo-ref="mongo"/>
    <!-- 不使用用户名密码 -->
    <!--    <mongo:db-factory  dbname="${mongo.databaseName}" mongo-ref="mongo"/>-->
    <bean id="MongoTemplate"
          class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>

--

简单的增删改查

实体类

--

点击查看代码
@Document(collection = "student")
@CompoundIndexes({
        @CompoundIndex(name = "idx_name_time", def = "{'name': 1, 'create_time':-1}")
})
public class Student{
    @Id
    private ObjectId id;
    @Field("name")
    private String name;
    @Field("create_time")
    private Date createTime;
}

--

仓储类

--

点击查看代码
@Repository
public class StudentDaoImpl implements StudentDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public int insert(Student student) {
        try{
            mongoTemplate.insert(student);
            return 1;
        }catch (Exception e){
            log.error("insert failed, ",e);
            return 0;
        }

    }

    @Override
    public List<Student> findList(StudentQueryDto queryDto) {
        Query query = new Query();

        Criteria criteria = new Criteria();

        if (null != queryDto.getName()) {
            criteria.and("name").is(queryDto.getName());
        }

        if (null != pointDataQueryDto.getStartTime() && null != pointDataQueryDto.getEndTime()) {
            criteria.andOperator(Criteria.where("create_time").gte(queryDto.getStartTime())
                    , Criteria.where("create_time").lt(queryDto.getEndTime()));
        } else if (null != queryDto.getStartTime()) {
            criteria.and("create_time").gte(queryDto.getStartTime());
        } else if (null != queryDto.getEndTime()) {
            criteria.and("create_time").lt(queryDto.getEndTime());
        }

        query.addCriteria(criteria);

        return new ArrayList<>(mongoTemplate.find(query, Student.class));
    }

    @Override
    public Long findListCount(StudentQueryDto queryDto) {
        Query query = new Query();

        Criteria criteria = Criteria.where("name").is(queryDto.getName())
                .andOperator(Criteria.where("create_time").gte(queryDto.getStartTime())
                        ,Criteria.where("create_time").lt(queryDto.getEndTime()));

        query.addCriteria(criteria);

        return mongoTemplate.count(query, Student.class);
    }

    @Override
    public long deleteByTime(Date startTime, Date endTime) {
        Criteria criteria =new Criteria();
        criteria.andOperator(Criteria.where("create_time").gte(startTime)
                ,Criteria.where("create_time").lt(endTime));
        Query query = new Query(criteria);
        WriteResult result = mongoTemplate.remove(query, PointData.class);
        long count = result.getN();
        return count;
    }
}
posted @ 2022-12-27 10:20  君子酱  阅读(354)  评论(1编辑  收藏  举报