我正在尝试使用反应式mongo库和spring数据构建应用程序。但是,每次我打应用程序并使用dao.findAll()
时,都会得到一个空数组。
请在下面找到代码。
/config/MongoAdminConfig.java
@EnableReactiveMongoRepositories
public class MongoAdminConfig extends AbstractReactiveMongoConfiguration {
@Override
@Bean
public MongoClient reactiveMongoClient() {
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mongodb://localhost:27017/projects"))
.build();
return MongoClients.create(settings);
}
@Override
protected String getDatabaseName() {
return "projects";
}
}
/controllers/AccountController.java
@RestController
@RequestMapping("accounts")
public class AccountController {
@Autowired
private AccountDao accountDao;
@GetMapping
public Flux<Account> getAllAccounts() {
return this.accountDao.findAll();
}
}
/dao/AccountDao.java
public interface AccountDao extends ReactiveCrudRepository<Account, String> {
}
/models/Account.java
@Document(collection = "accounts")
public class Account {
@Id
private String id;
private String accountNumber;
private String type;
private String status;
private double availableBalance;
private String currency;
//getters and setters
}
数据库查询示例
> db.accounts.find({})
{ "_id" : ObjectId("5deb40c43e079db50337b211"), "accountNumber" : "BANK123456", "type" : "savings", "status" : "active", "availableBalance" : 10000.5, "currency" : "USD" }
> db
projects
>
/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.aditapillai.demos</groupId>
<artifactId>accounts-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<version>2.2.1.RELEASE</version>
<artifactId>spring-boot-starter-parent</artifactId>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
</project>
可以在GitHub
上找到该代码平台详细信息:
操作系统:Ubuntu 19.04 LTS
Mongo版本:4.2.1
我的mongo服务器在本地计算机上的端口27017
上运行
这是一个新的mongo安装。
答案 0 :(得分:0)
通过执行以下操作固定。
已删除/config/MongoAdminConfig.java
/Application.java
@SpringBootApplication
@EnableReactiveMongoRepositories
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
src/main/resources/application.yml
spring:
data:
mongodb:
host: localhost
port: 27017
database: projects
我将继续了解这里到底发生了什么。