🎉 Sealos 首充折扣,限时返场!最高立返 10000,活动日期 4月22日-4月28日
Sealos Logo

Java

在 Sealos DevBox 中使用 Java 连接并操作 MongoDB 数据库的详细指南

本教程将详细介绍如何在 Sealos DevBox 项目中使用 Java 语言连接和操作 MongoDB 数据库。

准备工作

项目配置

创建 Maven 项目

在 Cursor 终端中执行以下命令创建一个新的 Maven 项目:

mvn archetype:generate -DgroupId=com.example -DartifactId=mongodb-java-example -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
mv mongodb-java-example/* .
rm -rf mongodb-java-example/

项目目录结构

完成配置后,项目的目录结构如下:

/
├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           ├── App.java
│   │   │           ├── MongoConfig.java
│   │   │           └── Employee.java
│   │   └── resources
│   │       └── mongodb.properties
│   └── test
│       └── java
│           └── com
│               └── example
│                   └── AppTest.java

配置 pom.xml 文件

pom.xml 文件内容替换为以下配置:

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.example</groupId>
    <artifactId>mongodb-java-example</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver-sync</artifactId>
            <version>5.2.0</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.5.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.App</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

上述配置文件包含了所需的依赖项 (MongoDB Java 驱动和 Logback 日志框架),并通过 Maven Shade 插件配置了可执行 JAR 包的生成。

创建配置文件

src/main/resources 目录下创建 mongodb.properties 配置文件:

mongodb.properties
mongodb.uri=mongodb://your_mongodb_host:27017
mongodb.database=your_database_name

请将配置文件中的占位符替换为您在 Sealos 数据库应用中获取的实际 MongoDB 连接信息。

创建 Java 类文件

src/main/java/com/example 目录下创建以下三个 Java 类:

  1. MongoConfig.java:用于加载 MongoDB 连接配置
MongoConfig.java
package com.example;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
 
public class MongoConfig {
    private static final Properties properties = new Properties();
 
    static {
        try (InputStream input = MongoConfig.class.getClassLoader().getResourceAsStream("mongodb.properties")) {
            if (input == null) {
                System.out.println("Sorry, unable to find mongodb.properties");
                System.exit(1);
            }
            properties.load(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static String getMongoUri() {
        return properties.getProperty("mongodb.uri");
    }
 
    public static String getDatabase() {
        return properties.getProperty("mongodb.database");
    }
}
  1. Employee.java:定义员工数据模型
Employee.java
package com.example;
 
import org.bson.Document;
 
public class Employee {
    private String id;
    private String name;
    private String position;
 
    public Employee(String name, String position) {
        this.name = name;
        this.position = position;
    }
 
    public Employee(Document doc) {
        this.id = doc.getObjectId("_id").toString();
        this.name = doc.getString("name");
        this.position = doc.getString("position");
    }
 
    public Document toDocument() {
        return new Document("name", name)
                .append("position", position);
    }
 
    @Override
    public String toString() {
        return "Employee{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", position='" + position + '\'' +
                '}';
    }
}
  1. App.java:主程序类,演示 MongoDB 基本操作
App.java
package com.example;
 
import com.mongodb.client.*;
import org.bson.Document;
 
public class App {
    public static void main(String[] args) {
        try (MongoClient mongoClient = MongoClients.create(MongoConfig.getMongoUri())) {
            MongoDatabase database = mongoClient.getDatabase(MongoConfig.getDatabase());
            MongoCollection<Document> collection = database.getCollection("employees");
 
            System.out.println("Connected to MongoDB");
 
            // Insert a document
            Employee newEmployee = new Employee("John Doe", "Developer");
            collection.insertOne(newEmployee.toDocument());
            System.out.println("Inserted a new employee");
 
            // Find all documents
            System.out.println("All employees:");
            try (MongoCursor<Document> cursor = collection.find().iterator()) {
                while (cursor.hasNext()) {
                    Employee employee = new Employee(cursor.next());
                    System.out.println(employee);
                }
            }
 
            // Update a document
            Document query = new Document("name", "John Doe");
            Document update = new Document("$set", new Document("position", "Senior Developer"));
            collection.updateOne(query, update);
            System.out.println("Updated John Doe's position");
 
            // Delete a document
            Document deleteQuery = new Document("name", "John Doe");
            collection.deleteOne(deleteQuery);
            System.out.println("Deleted John Doe from the database");
 
        } catch (Exception e) {
            System.err.println("Error connecting to MongoDB: " + e.getMessage());
        }
    }
}

主程序类展示了以下 MongoDB 基本操作:

  • 连接 MongoDB 数据库
  • 插入员工文档
  • 查询并显示所有员工信息
  • 更新员工职位
  • 删除员工记录

构建和运行

执行以下命令来构建并运行项目:

mvn clean package
java -jar target/mongodb-java-example-1.0-SNAPSHOT.jar

如果配置正确,您将看到一系列 MongoDB 操作的执行结果。

最佳实践

  1. 将 MongoDB 连接信息统一存储在配置文件中,便于管理和修改
  2. 创建专门的配置类来管理 MongoDB 连接参数
  3. 使用 try-with-resources 语句确保 MongoClient 资源的自动释放
  4. 合理处理异常情况,提供清晰的错误提示信息
  5. 使用 Maven 进行项目依赖管理和构建自动化

常见问题排查

如果遇到连接问题,请按以下步骤进行排查:

  1. 检查 mongodb.properties 文件中的连接信息是否正确
  2. 确认 MongoDB 数据库服务是否正常运行,且可以从 DevBox 环境访问
  3. 检查 DevBox 环境的网络设置是否有访问限制
  4. 验证 pom.xml 中的 MongoDB Java 驱动依赖配置是否正确
  5. 确保使用的 Java 版本符合要求 (本示例使用 OpenJDK 17)

如需了解更多 Java 操作 MongoDB 的详细信息,请参考 MongoDB Java 驱动官方文档

在 GitHub 上编辑

最后更新于

本页导航