美文网首页
spring mongo整合编程

spring mongo整合编程

作者: Stringer | 来源:发表于2017-04-07 22:19 被阅读232次

    maven:

    <dependency>
                <groupId>org.mongodb</groupId>
                <artifactId>mongo-java-driver</artifactId>
                <version>3.4.2</version>
            </dependency>
            <dependency>
                <groupId>com.google.code.gson</groupId>
                <artifactId>gson</artifactId>
                <version>2.8.0</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.data</groupId>
                <artifactId>spring-data-mongodb</artifactId>
                <version>1.9.5.RELEASE</version>
            </dependency>```
    
    spring-mongodb.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}"
    write-number="1"
    write-timeout="0"
    write-fsync="true" />
    </mongo:mongo>

    <!-- mongo数据库连接名称 -->
    <mongo:db-factory dbname="${mongo.db.name}" mongo-ref="mongo" username="${mongo.userName}" password="${mongo.password}"/>
    
    <!-- mongo数据库操作模板 -->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>
    
    <!-- MongoDB Dao层Bean配置 -->
    <bean id="mongodbDao" class="com.alsfox.dao.mongodb.MongodbDao">
        <property name="collectionName" value="${mongodb.collection.name}"/>
        <property name="mongoTemplate" ref="mongoTemplate"/>
    </bean>```
    

    MongodbDao.java

    package com.alsfox.dao.mongodb;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.data.domain.Sort;
    import org.springframework.data.domain.Sort.Direction;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;
    
    import com.alsfox.entity.DeviceState;
    import com.mongodb.BasicDBObject;
    import com.mongodb.DBCollection;
    import com.mongodb.DBObject;
    
    public class MongodbDao {
    
        // Mongo集合名称
        private String collectionName;
    
        // Mongo操作模板
        private MongoTemplate mongoTemplate;
    
        public void setCollectionName(String collectionName) {
            this.collectionName = collectionName;
        }
    
        public void setMongoTemplate(MongoTemplate mongoTemplate) {
            this.mongoTemplate = mongoTemplate;
        }
    
        /**
         * 批量插入mongodb
         *
         * @param deviceStateList
         */
        public void insertDeviceBeatStates(List<DeviceState> deviceStateList) {
            List<DBObject> dbObjectList = new ArrayList<DBObject>();
            for (int i = 0; i < deviceStateList.size(); i++) {
                DBObject dbObject = new BasicDBObject();
                dbObject.put("frameNo", deviceStateList.get(i).getFrameNo());
                dbObject.put("motorcar_state", deviceStateList.get(i).getMotorcar_state());
                dbObject.put("security_state", deviceStateList.get(i).getSecurity_state());
                dbObject.put("device_speed", deviceStateList.get(i).getDevice_speed());
                dbObject.put("battery_voltage", deviceStateList.get(i).getBattery_voltage());
                dbObject.put("battery_power", deviceStateList.get(i).getBattery_power());
                dbObject.put("motor_temperature", deviceStateList.get(i).getMotor_temperature());
                dbObject.put("control_temperature", deviceStateList.get(i).getControl_temperature());
                dbObject.put("battery_temperature", deviceStateList.get(i).getBattery_temperature());
                dbObject.put("stall", deviceStateList.get(i).getStall());
                dbObject.put("accelerate_num", deviceStateList.get(i).getAccelerate_num());
                dbObject.put("deceleration_num", deviceStateList.get(i).getDeceleration_num());
                dbObject.put("lon_flag", deviceStateList.get(i).getLon_flag());
                dbObject.put("lon_int", deviceStateList.get(i).getLon_int());
                dbObject.put("lon_float", deviceStateList.get(i).getLon_float());
                dbObject.put("lat_flag", deviceStateList.get(i).getLat_flag());
                dbObject.put("lat_int", deviceStateList.get(i).getLat_int());
                dbObject.put("lat_float", deviceStateList.get(i).getLat_float());
                dbObject.put("mileage", deviceStateList.get(i).getMileage());
                dbObject.put("createTime", deviceStateList.get(i).getCreateTime());
    
                dbObjectList.add(dbObject);
            }
    
            DBCollection dbCollection = mongoTemplate.getCollection(collectionName);
            dbCollection.insert(dbObjectList);
        }
    
        /**
         * 根据车架号查询倒数第二条数据
         *
         * @param carFrameNo
         * @return
         */
        public DeviceState selectLastFrameState(String carFrameNo) {
            Query query = new Query();
            Criteria criteria = new Criteria();
            criteria.andOperator(Criteria.where("frameNo").is(carFrameNo));
            query.addCriteria(criteria);
            query.with(new Sort(Direction.DESC, "createTime"));
            query.skip(1);
            query.limit(1);
            List<DeviceState> state = mongoTemplate.find(query, DeviceState.class, collectionName);
            if (state != null && state.size() > 0) {
                return state.get(0);
            } else {
                return null;
            }
        }
    
        /**
         * 根据车架号查询上一次位置信息
         *
         * @param carFrameNo
         * @return
         */
        public DeviceState selectLastLocationState(String carFrameNo) {
            Query query = new Query();
            Criteria criteria = new Criteria();
            criteria.andOperator(Criteria.where("frameNo").is(carFrameNo));
            query.addCriteria(criteria);
            //按时间倒序排列
            query.with(new Sort(Direction.DESC, "createTime"));
            query.limit(100);
            List<DeviceState> state = mongoTemplate.find(query, DeviceState.class, collectionName);
            if (state != null && state.size() > 0) {
                //遍历结果集
                for (DeviceState d : state) {
                    //判断是否有位置信息
                    if (d.getLon_int()[0] != 0) {
                        //有则返回
                        return d;
                    }
                }
            }
            return null;
        }
    
    
    }
    

    相关文章

      网友评论

          本文标题:spring mongo整合编程

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