gpt4 book ai didi

java - 基本 MongoOperations 调用返回零

转载 作者:太空宇宙 更新时间:2023-11-04 07:16:40 25 4
gpt4 key购买 nike

刚刚开始使用 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
>

我有什么遗漏吗?

最佳答案

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

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

您正在 Collection Camera 中查找使用db.Camera.count()

关于java - 基本 MongoOperations 调用返回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com