JavaでMongoDBを使い始めたばかりです。
次の 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
>
足りないものはありますか?