刚开始使用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
>
我有什么遗失的吗?
答案 0 :(得分:1)
@Document(collection = "cameras")
public class Camera {
Camera
已映射到代码中的集合cameras
。
您正在使用Camera
db.Camera.count()