如何防止 Spring Data MongoDB 将 id 字段映射为对象 id? [英] How to prevent Spring Data MongoDB from mapping id field as object id?

查看:33
本文介绍了如何防止 Spring Data MongoDB 将 id 字段映射为对象 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了自己的机制来为我的域对象分配身份,因此在持久化它们时,跟踪 MongoDB 分配给它们的内容对我来说确实没有太大价值.但是,我将域类的标识字段命名为 id,因为它简洁易懂.问题是,根据到文档,Spring 会自动将此字段映射到 MongoDB 分配的 ObjectID.我如何防止这种情况发生,而不必重命名我的 id 字段,或者定义一个用 @Id 注释的自定义标识字段只是为了解决这个问题?

I have set up my own mechanism for assigning identities to my domain objects, and so when persisting them, there really isn't much value for me to keep track of what MongoDB assigns to them. However, I name the identity fields for my domain classes id because, well, it's concise and understandable. The problem is that, according to the documentation, Spring will automatically map this field to MongoDB's assigned ObjectID. How do I prevent this from happening without having to rename my id field, or defining a custom identity field annotated with @Id just for the sake of working around this?

推荐答案

使用 @MongoId 而不是 @Id

Use @MongoId instead of @Id

@MongoId(targetType = FieldType.STRING)
protected String id;

即使形状"是 ObjectId,它也会存储字符串

It will store String even if the "shape" is an ObjectId

这篇关于如何防止 Spring Data MongoDB 将 id 字段映射为对象 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆