美文网首页
Spring集成mongoDB

Spring集成mongoDB

作者: 回首又十年 | 来源:发表于2020-09-12 14:38 被阅读0次

    1.pom文件引入

    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-mongodb</artifactId>
      <version>1.4.2.RELEASE</version>
    </dependency>
    
    <dependency>
       <groupId>org.mongodb</groupId>
       <artifactId>mongo-java-driver</artifactId>
       <version>2.14.2</version>
    </dependency>
    
    

    2.properties

    mongo.username=
    mongo.password=
    mongo.dbname=
    mongo.host=
    mongo.port=27017
    mongo.connectionsPerHost=40
    mongo.threadsAllowedToBlockForConnectionMultiplier=5
    #连接超时时间
    mongo.connectTimeout=60000
    #等待时间mongo.maxWaitTime=2000
    mongo.autoConnectRetry=true
    mongo.socketKeepAlive=true
    # socket超时时间
    mongo.socketTimeout=60000
    mongo.slaveOk=true
    

    3.xml 文件

    <mongo:mongo host="${mongo.host}" port="${mongo.port}">
        <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}"
                auto-connect-retry="${mongo.autoConnectRetry}"
                socket-keep-alive="${mongo.socketKeepAlive}"
                socket-timeout="${mongo.socketTimeout}"
                slave-ok="${mongo.slaveOk}"/>
    </mongo:mongo>
    
    <mongo:db-factory dbname="${mongo.dbname}" mongo-ref="mongo" username="${mongo.username}" password="${mongo.password}"/>
    
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>
    

    4.代码

    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.stereotype.Component;
    
    import javax.annotation.Resource;
    
    @Component
    public class UserDAO {
    
        @Resource
        protected MongoTemplate mongoTemplate;
    
        public UserPO findUser(Integer userId) {
            Criteria criteria = Criteria.where("userId").is(userId);
            Query query = Query.query(criteria);
            UserPO user = mongoTemplate.find(query, UserPO.class, "user");
            return user;
        }
    }
    

    相关文章

      网友评论

          本文标题:Spring集成mongoDB

          本文链接:https://www.haomeiwen.com/subject/zoswektx.html