1

刚开始使用 MongoDB 和 JAVA。

设置以下 JavaObject

package com.foo.bar

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "cameras")
public class Camera {

    @Id
    private int id= -1;
    String name = "";
    String orientation = "";
    boolean tempdis = false;
    int refreshRate = -1;
    String cityCode = "";
    String provider = "";
    Location location;
    //Gets & Sets Below
}

然后我有以下配置

package com.foo.bar.config

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.MongoClient;

@Configuration
public class SpringMongoConfig {

    public @Bean
    MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(), "myDB");
    }

    public @Bean
    MongoTemplate mongoTemplate() throws Exception {

        MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());

        return mongoTemplate;

    }

}

在我的主要应用程序中

package com.foo.bar

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

import com.foo.bar.config.SpringMongoConfig;
import com.foo.bar.Camera;

@Configuration
@EnableMongoRepositories
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(
                SpringMongoConfig.class);
        MongoOperations mongoOperation = (MongoOperations) ctx
                .getBean("mongoTemplate");

        List<Camera> listUser = mongoOperation.findAll(Camera.class);

        System.out.println(listUser.size());

    }
}

运行此代码使我的大小为 0。但是,在命令行中,我得到以下信息

C:\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.8
connecting to: test
> use myDB
switched to db myDB
> db.Camera.count()
1018
>

有什么我想念的吗?

4

1 回答 1

1
@Document(collection = "cameras")
public class Camera {

Camera映射到cameras代码中的集合。

并且您正在Camera使用db.Camera.count()

于 2013-11-08T20:31:11.047 回答