jaf*_*yed 6 java mongodb spring-data-mongodb spring-boot
您好,我正在尝试在 Spring Boot 中成功连接后导出MongoClient,并尝试在其他文件中使用它,这样我就不必每次需要在 MongoDB 数据库中进行更改时都调用该连接。
连接非常简单,但目标是将应用程序连接到我的数据库一次,然后通过将其导入到任何 Java 文件中,在任何我想要的地方使用它。
谢谢
以下是创建实例的几种方法MongoClient以下是在 Spring Boot 应用程序中创建、配置和使用
(1) 使用基于Java的元数据注册Mongo实例:
@Configuration
public class AppConfig {
public @Bean MongoClient mongoClient() {
return MongoClients.create();
}
}
Run Code Online (Sandbox Code Playgroud)
CommandLineRunner方法的用法run(所有示例的运行方式类似):
@Autowired
MongoClient mongoClient;
// Retrieves a document from the "test1" collection and "test" database.
// Note the MongoDB Java Driver API methods are used here.
private void getDocument() {
MongoDatabase database = client.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("test1");
Document myDoc = collection.find().first();
System.out.println(myDoc.toJson());
}
Run Code Online (Sandbox Code Playgroud)
(2) 使用 AbstractMongoClientConfiguration 类进行配置并与 MongoOperations 一起使用:
@Configuration
public class MongoClientConfiguration extends AbstractMongoClientConfiguration {
@Override
public MongoClient mongoClient() {
return MongoClients.create();
}
@Override
protected String getDatabaseName() {
return "newDB";
}
}
Run Code Online (Sandbox Code Playgroud)
newDB请注意,您可以设置可以连接的数据库名称 ( )。此配置用于使用 Spring Data MongoDB API 来处理 MongoDB 数据库:(MongoOperations及其实现MongoTemplate)和MongoRepository.
@Autowired
MongoOperations mongoOps;
// Connects to "newDB" database, and gets a count of all documents in the "test2" collection.
// Uses the MongoOperations interface methods.
private void getCollectionSize() {
Query query = new Query();
long n = mongoOps.count(query, "test2");
System.out.println("Collection size: " + n);
}
Run Code Online (Sandbox Code Playgroud)
(3)使用AbstractMongoClientConfiguration类进行配置并与MongoRepository一起使用
使用相同的配置MongoClientConfiguration类(上面主题 2 中的),但另外用 进行注释@EnableMongoRepositories。在这种情况下我们将使用MongoRepository接口方法来获取 Java 对象形式的集合数据。
存储库:
@Repository
public interface MyRepository extends MongoRepository<Test3, String> {
}
Run Code Online (Sandbox Code Playgroud)
Test3.java代表集合文档的 POJO类test3:
public class Test3 {
private String id;
private String fld;
public Test3() {
}
// Getter and setter methods for the two fields
// Override 'toString' method
...
}
Run Code Online (Sandbox Code Playgroud)
以下方法获取文档并打印为 Java 对象:
@Autowired
MyRepository repository;
// Method to get all the `test3` collection documents as Java objects.
private void getCollectionObjects() {
List<Test3> list = repository.findAll();
list.forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20836 次 |
| 最近记录: |