Java MongoDb 获取 id 作为时间戳但需要十六进制字符串

Java MongoDb getting id as a timestamp but need the hexadecimal string

我正在为名为 Schema 的集合执行 CRUD,需要将 de _id 检索为十六进制字符串,但是当我使用 collection.find() 时,我得到的是时间戳和日期而不是字符串。

我正在接收这个结构:

{
"_id": {
            "timestamp": 1604689898,
            "date": "2020-11-06T19:11:38.000+00:00"
        }
}

但我需要这样的东西:

{
"_id": "5fa5a085a4b09b307d53ed57"
}

这是我的配置

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>co.com.itau</groupId>
    <artifactId>crypto-mongodb-java-ms</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>crypto-mongodb-java-ms</name>
    <description>Microservice to save and read data from mongoDB using CSFLE</description>

    <properties>
        <java.version>1.8</java.version>
        <version.fabric8-maven-plugin>3.5.41</version.fabric8-maven-plugin>
        <swagger.version>3.0.0</swagger.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency> 
            <groupId>io.springfox</groupId> 
            <artifactId>springfox-boot-starter</artifactId> 
            <version>${swagger.version}</version> 
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>
          <dependency>
            <groupId>org.springframework.plugin</groupId>
            <artifactId>spring-plugin-core</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-crypt</artifactId>
            <version>1.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
    <profiles>
        <profile>
            <id>openshift</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>io.fabric8</groupId>
                        <artifactId>fabric8-maven-plugin</artifactId>
                        <version>${version.fabric8-maven-plugin}</version>
                        <executions>
                            <execution>
                                <id>fmp</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>resource</goal>
                                    <goal>build</goal>
                                </goals>
                            </execution>
                        </executions>
                        <configuration>
                            <generator>
                                <config>
                                    <spring-boot>
                                        <fromMode>isTag</fromMode>
                                        <from>redhat-openjdk18-openshift:1.2</from>
                                    </spring-boot>
                                </config>
                            </generator>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>

MongoClient配置

CodecRegistry pojoCodecRegistry = fromProviders(PojoCodecProvider.builder().automatic(true).build());
        CodecRegistry codecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), pojoCodecRegistry);
        
        MongoClient mongoAux = MongoClients.create(MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString(connectionString))
                .codecRegistry(codecRegistry)
                .build());
        
        return mongoAux;

架构模型

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Schema {
    
    @JsonProperty("_id")
    @SerializedName("_id")
    public ObjectId id;

    public String db;
    
    public String collection;
    
    public Document schema;
}

** 存储库 **

@Repository
public class SchemaMongoRepository implements SchemaRepository{


    @Value("${mongodb.schema.db}")
    private String mongoDatabase;

    @Value("${mongodb.schema.collection}")
    private String mongoCollection;
    
    
    private static final Logger logger = LoggerFactory.getLogger(SchemaMongoRepository.class);

    @Autowired
    private MongoClient mongoClient;
    
    @Autowired
    private DataKey datakey;
    
    private MongoCollection<Schema> schemaCollection;
    
    @PostConstruct
    void init() {
        schemaCollection = mongoClient.getDatabase(mongoDatabase).getCollection(mongoCollection, Schema.class);
    }

    @Override
    public List<Schema> getSchemas() {
    
        List<Schema> schemaList = new ArrayList<Schema>();
        FindIterable<Schema> result = schemaCollection.find();
        
        for(Schema currentSchema: result) {
            schemaList.add(currentSchema);
        }
        return schemaList;
    }
}

您面临的问题是 ObjectId 被扩展(反序列化)。我们在 pom

中实现 serialization.Add 这个依赖
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0.rc1</version>
</dependency>

在main中添加如下方法class.

@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer()
{
    return builder -> builder.serializerByType(ObjectId.class,new ToStringSerializer());
}

这将为您提供预期的输出。

就我而言,使用 Kotlin 非常简单,只需添加一个 Jackson JSON 序列化程序:

@JsonSerialize(using = ToStringSerializer::class)
val id: ObjectId = ObjectId.get(),

为了获得:

{
    "id": "622b34af87c70514f6452363",
    ...
}

而不是:

{
    "id": {
        "timestamp": 1646998703,
        "date": "2022-03-11T11:38:23.000+00:00"
    },
    ...
}